JSON with HTTP Requests - potatoscript/json GitHub Wiki
π‘ JSON with HTTP Requests: Mastering Data Exchange! π
Welcome to the World of HTTP Requests and JSON! ππ¨
When you visit a website, submit a form, or interact with an app, HTTP requests are happening behind the scenes!
And guess what? JSON is the superhero format used to transfer data! π¦ΈββοΈπ
π― What is an HTTP Request?
- HTTP (HyperText Transfer Protocol):
A protocol that allows communication between a client (browser/app) and a server. π‘π
π Basic Workflow:
- π¨ Client Sends a Request: The browser or app sends an HTTP request to the server.
- π‘ Server Processes the Request: The server processes the request and sends a response.
- π© Client Receives the Response: The response is usually in JSON format, which the client processes and displays.
πΉοΈ 1. Types of HTTP Requests
π₯ Method | π Action | π― Purpose |
---|---|---|
GET |
Retrieve Data | Fetch data from the server. |
POST |
Create Data | Add new data to the server. |
PUT |
Update/Replace Data | Update or replace existing data. |
PATCH |
Modify/Partially Update | Update only specific fields. |
DELETE |
Remove Data | Delete data from the server. |
π© 2. How Does JSON Work with HTTP Requests?
When sending and receiving data over HTTP, JSON is used in the body of the request and response.
π― Example: Basic JSON Workflow with HTTP Requests
Client: "Hey Server, give me the list of users!"
Request:
GET /users HTTP/1.1
Host: api.example.com
Server: "Hereβs the list of users in JSON format!"
Response:
HTTP/1.1 200 OK
Content-Type: application/json
[
{
"id": 1,
"name": "Lucy Berry",
"age": 26
},
{
"id": 2,
"name": "Bruce",
"age": 35
}
]
β Explanation:
- The client sends a GET request.
- The server responds with a JSON array of user data.
π 3. Sending JSON Data with HTTP Requests
π¨ a) Sending JSON with POST Request
When adding data to a server, you use a POST request.
π― Example: Sending JSON with POST Request
let userData = {
name: "Lucy Berry",
age: 26,
hobbies: ["reading", "coding"]
};
// Send POST request
fetch("https://api.example.com/users", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(userData)
})
.then(response => response.json())
.then(data => console.log("User added:", data))
.catch(error => console.error("Error:", error));
β Explanation:
fetch()
sends a POST request to the URL.headers
specify that the content isapplication/json
.JSON.stringify(userData)
converts the JavaScript object to a JSON string.
π b) Sending JSON with PUT Request
To update or replace data, you use a PUT request.
π― Example: Updating Data with PUT Request
let updatedUser = {
name: "Lucy Berry",
age: 27
};
// Send PUT request to update data
fetch("https://api.example.com/users/1", {
method: "PUT",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(updatedUser)
})
.then(response => response.json())
.then(data => console.log("User updated:", data))
.catch(error => console.error("Error:", error));
β Explanation:
PUT
sends data to update a resource.body: JSON.stringify(updatedUser)
converts the object to JSON.
π c) Sending Partial Data with PATCH Request
If you only want to update specific fields, use PATCH.
π― Example: Partial Update with PATCH Request
let partialUpdate = {
age: 28
};
// Send PATCH request to modify age only
fetch("https://api.example.com/users/1", {
method: "PATCH",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(partialUpdate)
})
.then(response => response.json())
.then(data => console.log("User updated:", data))
.catch(error => console.error("Error:", error));
β Explanation:
PATCH
updates only the specified field (age
).- Ideal for modifying part of an object.
π‘ 4. Receiving and Parsing JSON with HTTP Responses
When the server responds, the data is usually in JSON format, which you need to parse before using.
π― Example: Fetching Data with GET Request
// Fetch data from API
fetch("https://api.example.com/users/1")
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json();
})
.then(data => {
console.log("User Name:", data.name);
console.log("User Age:", data.age);
})
.catch(error => console.error("Error:", error));
β Explanation:
fetch()
sends a GET request.response.json()
converts JSON to a JavaScript object.- Data is printed using
console.log()
.
π 5. Deleting Data with JSON and HTTP Requests
To delete data, use the DELETE method.
π― Example: Deleting Data with DELETE Request
// Delete user with ID 1
fetch("https://api.example.com/users/1", {
method: "DELETE"
})
.then(response => {
if (response.ok) {
console.log("User deleted successfully.");
} else {
console.error("Failed to delete user.");
}
})
.catch(error => console.error("Error:", error));
β Explanation:
DELETE
removes the user from the server.- If successful, a confirmation message is logged.
π¦ 6. Handling JSON Headers with HTTP Requests
Headers provide extra information about the request/response.
For JSON, use Content-Type: application/json
.
π― Example: Sending Headers with Fetch
let data = {
name: "Lucy Berry",
age: 26
};
// Send data with headers
fetch("https://api.example.com/users", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer my-secret-token"
},
body: JSON.stringify(data)
})
.then(response => response.json())
.then(data => console.log("User added:", data))
.catch(error => console.error("Error:", error));
β Explanation:
Content-Type
specifies the format (application/json
).Authorization
sends a token for secure requests.
π‘ 7. Sending Query Parameters in HTTP Requests
You can add query parameters to a URL to send extra information.
π― Example: Sending Query Parameters
let url = "https://api.example.com/users?age=25&name=Lucy";
// Fetch data with query parameters
fetch(url)
.then(response => response.json())
.then(data => console.log("Filtered data:", data))
.catch(error => console.error("Error:", error));
β Explanation:
?age=25&name=Lucy
sends parameters to the API.- The server filters the data based on the query.
π₯ 8. Handling API Errors Gracefully
APIs donβt always behave as expected!
Handle errors using try...catch
or .catch()
. π‘οΈ
π― Example: Error Handling with Fetch
// Fetch data with error handling
fetch("https://api.example.com/users/999")
.then(response => {
if (!response.ok) {
throw new Error(`Error: ${response.status} - ${response.statusText}`);
}
return response.json();
})
.then(data => console.log("User data:", data))
.catch(error => console.error("Error fetching data:", error.message));
β Explanation:
response.ok
checks if the response was successful..catch()
handles any network or processing errors.
π§© 9. Sending Form Data with JSON
If youβre sending form data, convert it to JSON before sending.
π― Example: Sending Form Data as JSON
let formData = {
name: document.getElementById("name").value,
email: document.getElementById("email").value
};
// Send form data with POST request
fetch("https://api.example.com/submit", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(formData)
})
.then(response => response.json())
.then(data => console.log("Form submitted:", data))
.catch(error => console.error("Error:", error));
β Explanation:
document.getElementById()
gets form input values.JSON.stringify()
converts the object to a JSON string.
πΉοΈ 10. Working with JSON and Promises in HTTP Requests
When you use fetch()
, it returns a Promise that resolves when the request is complete.
π― Example: Handling Promises with Fetch
fetch("https://api.example.com/users")
.then(response => response.json())
.then(data => console.log("Data fetched:", data))
.catch(error => console.error("Error:", error));
β Explanation:
.then()
handles the successful response..catch()
handles errors in the request.