-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.js
More file actions
203 lines (154 loc) · 4.52 KB
/
api.js
File metadata and controls
203 lines (154 loc) · 4.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
/*
======================== API REVISION NOTES ========================
API = Application Programming Interface
→ It allows two applications (client & server) to communicate.
Client = Browser / Frontend
Server = Provides data
Request → sent by client
Response → returned by server
fetch() → used to send HTTP requests in JavaScript.
It returns a Promise.
Promise = An object that represents a value that will come in the future.
async → makes a function asynchronous.
await → pauses execution until Promise is resolved.
Common HTTP Methods:
GET → Get data from server
POST → Send new data to server
PUT → Update existing data
DELETE → Remove data
Most APIs return data in JSON format.
JSON = JavaScript Object Notation
→ Lightweight data format used to exchange data.
→ Looks like JavaScript objects but is actually text.
response.json()
→ Converts JSON data into JavaScript object.
API call steps:
1. Send request using fetch()
2. Wait for response (await)
3. Convert response to JSON
4. Use the data
Example response structure:
{
data: [
{ fact: "Cats sleep 70% of their lives", length: 30 }
]
}
To access first fact:
data.data[0].fact
AJAX = Asynchronous JavaScript and XML
→ Old technique to fetch data (mostly used XML earlier)
→ Now JSON is more common.
APIs are asynchronous because network requests take time.
====================================================================
*/
const url = "https://catfact.ninja/facts?limit=5"
let b = document.querySelector(".btn")
//fetch api - provides an interface for sending and receinving resourses
//returns promise;
const getfacts = async () => {
let response = await fetch(url)//this is GET REQUEST(promise) request is sent to website;
console.log(response)//json format....api return format in json format--asaj
let data = await response.json();//promis 2 in js obj
console.log(data);//this is an object;
console.log(data.data);//array
b.innerText = data.data[0].fact
}
getfacts()
//https code;
// 200 → Success
// 👉 201 → Created
// 👉 400 → Bad request
// 👉 401 → Not authorized
// 👉 404 → Not found
// 👉 500 → Server error
/*
==================== HTTP METHODS (POST, PUT, DELETE) ====================
All network requests use fetch().
fetch() is asynchronous → it returns a Promise.
So we use async/await or .then() to handle it.
--------------------------------------------------------------------------
1️⃣ POST → Create New Data
Purpose:
Used to add/create new data on the server.
Example:
fetch("https://example.com/students", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
name: "Divisha",
age: 20
})
})
What happens internally:
- Data is sent to server
- Server creates new record
- Server assigns an ID
- Server sends created object back
Use POST when:
- Registering user
- Adding product
- Submitting form
- Creating new post
IMPORTANT:
POST usually needs headers + body + JSON.stringify()
--------------------------------------------------------------------------
2️⃣ PUT → Update/Replace Existing Data (Full Update)
Purpose:
Used to completely replace existing data.
Example:
fetch("https://example.com/students/1", {
method: "PUT",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
id: 1,
name: "Divisha Updated",
age: 22
})
})
What happens internally:
- Server finds record by ID
- Old data is fully replaced
- Updated data is saved
- Updated object is returned
IMPORTANT:
PUT replaces the entire object.
If some fields are missing, they may be removed.
Use PUT when:
- Updating full profile
- Editing complete product info
- Replacing full record
--------------------------------------------------------------------------
3️⃣ DELETE → Remove Data
Purpose:
Used to delete data from server.
Example:
fetch("https://example.com/students/1", {
method: "DELETE"
})
What happens internally:
- Server finds record
- Deletes it
- Sends success response (200 or 204)
Use DELETE when:
- Deleting account
- Removing post
- Deleting product
DELETE usually does NOT need body.
--------------------------------------------------------------------------
🔥 SIMPLE MEMORY RULE
POST → Create new data
PUT → Replace full data
DELETE → Remove data
POST & PUT → Need JSON.stringify() + headers
DELETE → Usually no body needed
All methods:
- Use fetch()
- Are asynchronous
- Return Promise
- Should use async/await
==========================================================================
*/