0% found this document useful (0 votes)
0 views

json_fetch

This document provides an overview of an API that allows developers to interact with a specific application for data management. It explains the structure and functionality of HTTP requests and responses, including methods, headers, and the importance of the Content-Type header. Additionally, it covers JSON as a data format and introduces the fetch() method in JavaScript for making network requests.

Uploaded by

xeroxxwala
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

json_fetch

This document provides an overview of an API that allows developers to interact with a specific application for data management. It explains the structure and functionality of HTTP requests and responses, including methods, headers, and the importance of the Content-Type header. Additionally, it covers JSON as a data format and introduces the fetch() method in JavaScript for making network requests.

Uploaded by

xeroxxwala
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

Introduction to the API

What is the API(Application Programming Interface)?

This API allows developers to interact with [Your App Name] for:

● Fetching data (e.g., products, users)


● Creating, updating, and deleting resources
How to Use This API
Base URL:

All API requests start with the following base URL: https://api.example.com/v1

Endpoints:

● Each endpoint represents a specific functionality (e.g., fetching items or adding a new item).
● Simply append the endpoint to the base URL.

Request Format:

● Use tools like Postman or code-based HTTP libraries like fetch (JavaScript) to send requests.
HTTP (HyperText Transfer Protocol)
HTTP (HyperText Transfer Protocol) is the foundational communication protocol used on the internet to
transfer data between clients (like web browsers or apps) and servers.

Whenever you open a website (like google.com), your browser sends an HTTP request to the server where
the website is hosted, and the server replies with an HTTP response.
Key Features of HTTP:

1. Client-Server Model:
○ The client sends requests (e.g., asking for a webpage).
○ The server processes the request and sends back a response (e.g., the webpage content).
2. Stateless:
○ Each request is independent of the previous one.
○ The server does not remember any information about past interactions.
3. Text-Based Protocol:
○ HTTP uses plain text for communication, making it human-readable.
How HTTP Works:
1:Request: The client sends an HTTP request to a server.

● Example: A browser requesting a webpage like https://example.com.

Parts of an HTTP Request:

● Request Line: Contains the HTTP method (GET, POST, etc.), the URL, and the HTTP
version.
● Headers: Extra information like Content-Type or User-Agent.
● Body: Data sent with the request (e.g., form data in a POST request)
2:Response: The server processes the request and sends back an HTTP
response.

● The response contains the requested data (e.g., the webpage).

Parts of an HTTP Response:

● Status Line: Indicates success or failure (e.g., 200 OK or 404 Not Found).
● Headers: Additional information (e.g., Content-Type or Content-Length).
● Body: The actual data (e.g., HTML content or JSON data)
What is inside HTTP?
Think of HTTP as a package you send across the internet.
It can be a Request (you asking for something) or a Response (the server replying to you).

Whether it’s a request or a response, the HTTP message usually has 3 main parts:
📦 Inside an HTTP Message

1. Start Line

2. Headers

3. Body (optional)
1. 🚀 Start Line
This tells what’s happening in the message.

📤 Request Example: GET /products HTTP/

GET: the HTTP method (like GET, POST, PUT, etc.)

/products: the resource or path you want

📥 Response Example: HTTP/1.1 200 OK

● 200 OK: the status code (means success)


● There are many status codes like:
○ 200: OK
○ 404: Not Found
○ 500: Server Error
2. 🧾 Headers
Headers are key-value pairs that carry extra information about the message.

💡 In a request, they tell:

● Who is making the request (User-Agent)


● What kind of data is being sent (Content-Type)
● Whether you’re logged in (Authorization)
● What data you want back (Accept)

Content-Type: application/json

Authorization: Bearer token123


3. 📄 Body (Optional)
"Body" part of HTTP — especially in POST and PUT requests, since these are most commonly used to send data from a client (like a
browser or app) to a server.

🧠 What is the HTTP Body?

The body is the actual content or data you are sending with your HTTP request or response.

● In GET requests, there’s usually no body — you’re just asking for something.

● In POST, PUT, or PATCH, you usually include a body, because you are sending data to the server.
⚠ What if you use the wrong Content-Type?

Let’s say you accidentally write:

Content-Type: text/plain

But your body contains JSON like:

{"name": "John"}

The server might say:

“Wait, I was expecting plain text but this looks like JSON. I don’t know what to do with it.”
Result: You get a 400 Bad Request error.
HTTP Methods:

GET: Request data from the server (e.g., fetch a webpage).

POST: Send data to the server (e.g., submitting a form).

PUT: Update existing data on the server.

DELETE: Remove data from the server.

PATCH: Partially update existing data.


Introduction to JSON (JavaScript Object Notation)

JSON (JavaScript Object Notation) is a lightweight, human-readable data format


used for storing and exchanging data. It is widely used in web applications to send
and receive data, especially in APIs.
Why JSON is the Standard Data Format?
1:Simple Syntax:

● JSON is easy to read and write, making it developer-friendly.


● It is less verbose than XML and more compact, which leads to faster transmission over
networks.

2:Language Independent:

● While JSON originated from JavaScript, it is language-independent and can be used by most
modern programming languages, including Python, Java, Ruby, PHP, and more.
3:Structured Data:

● JSON organizes data in a key-value pair format, which is intuitive for representing objects or
structured data.

4:Easy to Parse:

● JSON is natively supported by JavaScript, and most languages have libraries to parse and
generate JSON data easily.
JSON Syntax and Structure

● Data is in name/value pairs


● Data is separated by commas
● Curly braces hold objects
● Square brackets hold arrays
Working with JSON in JavaScript

1. Parsing JSON (Converting JSON String to JavaScript Object)


When JSON data is received from an API or a server, it often comes as a string (e.g., when
sent in HTTP responses). To use that data in your JavaScript code, you need to convert it
from a JSON string to a JavaScript object. This is where JSON.parse() comes in.
Why use JSON.parse()?

● To Convert JSON String to JavaScript Object: JSON is typically transmitted as a string, but
we need a JavaScript object to easily manipulate the data.
● For Working with the Data: Once the data is in object form, you can access its properties and
manipulate it like any other JavaScript object.
2. Stringifying JavaScript Objects (Converting JavaScript Object to JSON String)
When you need to send data from JavaScript to a server (for example, in an HTTP POST
request), you often need to convert a JavaScript object into a JSON string. This is where
JSON.stringify() is used.

Why use JSON.stringify()?

● To Convert JavaScript Object to JSON String: Servers often expect data in JSON
format, so we need to turn our JavaScript object into a JSON string before sending it.
● For Sending Data to APIs: When making API requests with POST or PUT, the data is
typically sent as a string in the body of the request.
Why do we need both JSON.parse() and JSON.stringify()?

Data comes as a string: When you receive data from a server (like in an API
response), it’s usually in the form of a string. But to use it in JavaScript (e.g.,
accessing properties like name, age), it needs to be converted into a JavaScript
object using JSON.parse().

Data needs to be a string for sending: Similarly, when sending data to a server, we
need to convert JavaScript objects into strings using JSON.stringify() because
servers expect the data in a string format (typically JSON).
These two methods are essential when working with APIs because they allow for
seamless conversion between the data format used by the server (JSON) and the
format used by JavaScript (objects).
Understanding fetch() in JavaScript

fetch() is a modern JavaScript method for making network requests, such as retrieving data
from an API or sending data to a server. It is a part of the Fetch API and provides a clean and
simple interface for working with HTTP requests.

What is fetch()?

● The fetch() method is used to make asynchronous requests to a server.


● It returns a Promise, which resolves to the response object representing the result of
the request.
● You can use fetch() to make GET, POST, PUT, DELETE, and other types of requests.
Syntax of fetch()

Parameters:

1. url: The endpoint or URL you want to make the request to (e.g., API endpoint).
2. options (optional): An object containing request configuration such as method,
headers, body, etc.

Returns:

● A Promise that resolves to the response.


Detailed Explanation of fetch() Parameters

1. url (Mandatory)

The url parameter is the address of the resource or endpoint you want to interact with,
such as an API or a file on a server. This is the only mandatory parameter in the fetch()
method.

2. options (Optional)

The options parameter is an object that allows you to customize the request. It
specifies the HTTP method, headers, body, mode, cache, and other configurations for
the request.
Common Properties in the options Object:

1:method (Optional):

● Defines the HTTP method for the request.


● Common methods:
○ GET: Retrieve data from the server (default).
○ POST: Send data to the server.
○ PUT: Update data on the server.
○ DELETE: Remove data from the server.

fetch('https://api.example.com/users', { method: 'POST' });


2:headers (Optional):
● Defines additional information to send along with the request.
● Often used to specify the type of data being sent (e.g., JSON) or include authentication
tokens.
● Common headers:
○ Content-Type: Specifies the format of the request body (e.g., application/json).
○ Authorization: Includes API tokens or authentication credentials.

fetch('https://api.example.com/users', {
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer myToken123'
}
});
Understanding Content-Type Header
The Content-Type header is used to specify the format of the data being sent in the body of a
request or being received in the response. It acts as a communication bridge between the client
(you) and the server to ensure both sides understand the type of data being exchanged.

Why Use Content-Type?


1. Server Understanding:
○ When you send data to a server (like in a POST or PUT request), the server needs to
know how to interpret the data.
○ For example:
■ Is the data plain text?
■ Is it JSON (JavaScript Object Notation)?
■ Is it a file (e.g., an image or PDF)?
○ The Content-Type header explicitly tells the server how to parse the data.
1. Client Understanding:
○ When a server sends back a response (like JSON or an HTML page), the
Content-Type header in the response tells your application how to handle the
data.
2. Avoiding Miscommunication:
○ Without the correct Content-Type, the server might not process your request
correctly, or the client might not display the response properly. This could lead
to bugs, errors, or broken features in your app.
How It Works
When you make an HTTP request with a body (e.g., for sending data), you specify the
Content-Type in the headers. This tells the server what kind of data you're sending.

1. Sending JSON Data (application/json)

This is the most common use case for modern APIs.

● Why Use It? JSON is lightweight, easy to read, and supported by most programming
languages. It’s the standard format for exchanging data between clients and servers.
headers: { 'Content-Type': 'application/json' // Tells the server you're sending JSON
},
How It Works:

1. The Content-Type: application/json tells the server, "Hey, I’m sending JSON data."
2. The server knows to parse the body as JSON (not plain text or some other format).
3. Without this header, the server might fail to parse the data or throw an error.

You might also like