Simplified API Calls: Making Life Easier with API Utility Function

Hardik Desai avatar
Hardik Desai

25 September 2024

2 min read
Simplified API Calls: Making Life Easier with API Utility Function

Description

Discover how using Axios wrapper functions can streamline your API calls, making integration effortless. This utility function handles various request types, authentication tokens, and data formats, enhancing the efficiency of your development process

Summary

🚀 Unlock the power of Axios wrapper functions to streamline API calls! This versatile utility handles different request types and authentication, making integration a breeze. Say goodbye to complex setups and hello to efficient development! 💻✨

Source Code

1
// ***** start - import from packages *****
2
import axios, { AxiosRequestConfig } from 'axios'
3
import Cookies from 'js-cookie'
4
import { ACCESS_TOKEN_KEY } from 'src/constants/constant'
5
6
// ***** end - import from packages *****
7
8
type requestType = 'get' | 'post' | 'delete' | 'postFormData' | 'postWithoutToken' | 'postFormDataWithoutToken'
9
10
// ***** start - Api function for call any type of apis *****
11
export const api = async (endpoint: string, data: any, type: requestType, configs?: AxiosRequestConfig<any>) => {
12
let res: any
13
const token = Cookies.get(ACCESS_TOKEN_KEY)
14
15
switch (type) {
16
case 'get':
17
res = await axios({
18
data,
19
method: 'get',
20
headers: {
21
'Content-Type': 'application/json',
22
Authorization: `Bearer ${token}`
23
},
24
url: endpoint,
25
...configs
26
})
27
break
28
case 'post':
29
res = await axios({
30
data,
31
method: 'post',
32
headers: {
33
'Content-Type': 'application/json',
34
Authorization: `Bearer ${token}`
35
},
36
url: endpoint,
37
...configs
38
})
39
break
40
case 'delete':
41
res = await axios({
42
data,
43
method: 'delete',
44
headers: {
45
'Content-Type': 'application/json',
46
Authorization: `Bearer ${token}`
47
},
48
url: endpoint,
49
...configs
50
})
51
break
52
case 'postWithoutToken':
53
res = await axios({
54
method: 'post',
55
data,
56
headers: {
57
'Content-Type': 'application/json'
58
},
59
url: endpoint,
60
...configs
61
})
62
break
63
case 'postFormData':
64
res = await axios({
65
data,
66
method: 'post',
67
headers: {
68
'Content-Type': 'multipart/form-data',
69
Authorization: `Bearer ${token}`
70
},
71
url: endpoint,
72
...configs
73
})
74
break
75
case 'postFormDataWithoutToken':
76
res = await axios({
77
data,
78
method: 'post',
79
headers: {
80
'Content-Type': 'multipart/form-data'
81
},
82
url: endpoint,
83
...configs
84
})
85
break
86
default:
87
return true
88
}
89
90
return res
91
}
92
93
// ***** end - Api function for call any type of apis *****

Join the newsletter

Subscribe for weekly updates. No spams ever!

Copyright © 2024 | Hardik Desai | All Rights Reserved