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:

  1. πŸ“¨ Client Sends a Request: The browser or app sends an HTTP request to the server.
  2. πŸ“‘ Server Processes the Request: The server processes the request and sends a response.
  3. πŸ“© 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 is application/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.