0% found this document useful (0 votes)
5 views19 pages

Rest Api

The document explains REST APIs as a communication layer between frontend and backend applications using HTTP methods for resource operations, typically exchanging data in JSON format. It also covers AJAX for asynchronous web server requests and introduces the Fetch API as a modern alternative for making API requests with Promises. Key concepts include client-server architecture, statelessness, and uniform interface for resource access.
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)
5 views19 pages

Rest Api

The document explains REST APIs as a communication layer between frontend and backend applications using HTTP methods for resource operations, typically exchanging data in JSON format. It also covers AJAX for asynchronous web server requests and introduces the Fetch API as a modern alternative for making API requests with Promises. Key concepts include client-server architecture, statelessness, and uniform interface for resource access.
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

R E S T AP I

Representational State Transfer (REST API) acts as the communication layer


between the frontend (client-side) and the backend (server-side) of an
application.

Communication Protocol: REST APIs primarily use HTTP methods (GET, POST,
PUT, DELETE) to perform operations on resources.

Data Format: The data exchanged between the frontend and backend
through a REST API is typically in a standardized format, most commonly
JSON (JavaScript Object Notation), although XML can also be used.
Core systems of REST
Key Concepts of R E S T AP I
Client-Server Architecture Stateless
• Client (frontend, e.g., React app, mobile app) → sends requests. Each request is independent. The server doesn't
• Server (backend, e.g., [Link], Django, remember your previous requests.
Spring) → processes requests and sends
responses.

E xample:
GET /books → get all books Resources
GET /books/1 → get book with ID 1
POST /books → add a new book Everything in REST is treated as a resource (user,
PUT /books/1 → update book with ID 1 product, book, order). Each resource is identified
DELETE /books/1 → delete book with ID 1 by a URL (endpoint).

HTTP Methods (CR UD Operations) Data Format


• GET → Read data REST APIs usually exchange data in JSON
• POST → Create new data
• PUT → Update existing data {
• DELETE → Remove data "id": 1,
"title": "Book One",
"author": "Author A“ }

Uniform Interface The way you access resources is consistent. Example: /users, /books, /orders all behave similarly.
AJ AX (Asynchronous J avaS cript
and XML)
AJAX is a technique to make asynchronous requests to the server without
reloading the whole web page. Earlier it used XMLHttpRequest (XHR), but
nowadays mostly JSON is used instead of XML.

Key Ideas:
• Asynchronous → The page doesn't freeze while waiting for server response.
• Update only part of the webpage (dynamic loading).

AJAX is a developer's dream, because you can:

• Update a web page without reloading the page


• Request data from a server - after the page has loaded
• Receive data from a server - after the page has loaded
• Send data to a server - in the background
How AJ AX Works - basics
01 02 03

E vent Occurs Object Creation R equest S ent


An event occurs in a web page (the page An XMLHttpRequest object is created by The XMLHttpRequest object sends a
is loaded, a button is clicked) JavaScript request to a web server

04 05 06

S erver Processing R esponse S ent R esponse R ead


The server processes the request The server sends a response back to the The response is read by JavaScript
web page

07

Action Performed
Proper action (like page update) is performed by JavaScript
Ajax simple Example
<!DOCTYPE html>
<html>
<body>
<div id="demo">
<h2>Let AJAX change this text</h2>
<button type="button" onclick="loadDoc()">Change
Content</button>
</div>
</body>
</html>
AJ AX S imple E xample

Let AJ AX change this text


Change Content

Function loadDoc()

function loadDoc() {
var xhttp = new XMLHttpRequest();
[Link] = function() {
if ([Link] == 4 && [Link] == 200) {
[Link]("demo").innerHTML = [Link];
} };
[Link]("GET", "ajax_info.txt", true);
[Link](); }
AJAX Simple Example

<h1>AJAX</h1>
<p>AJAX is not a programming language.</p>
<p>AJAX is a technique for accessing web servers from a web page.</p>
<p>AJAX stands for Asynchronous JavaScript And XML.</p>
Fetch AP I
Fetch API is a modern replacement for AJAX/XHR.
Uses Promises (and can use async/await). Cleaner
and easier to read.
How Fetch API is used in Full Stack
Frontend to Backend Communication:

Making API Requests Retrieving Data Sending Data


Frontend JavaScript code uses fetch() fetch() is commonly used to retrieve fetch() allows sending data to the
to send requests (GET, POST, PUT, data from the backend, such as user backend, for example, submitting
DELETE, etc.) to specific API endpoints information, product lists, or blog form data, creating new resources, or
exposed by the backend. posts. updating existing ones.
Handling Responses
Promises Processing Data Error Handling
fetch() returns a Promise, The Response object .catch() blocks are used to
which resolves to a contains information handle network errors or
Response object upon about the response other issues that prevent
successful completion of (status, headers, etc.). The the request from
the request. actual data (e.g., JSON) is completing. It is important
extracted using methods to also check [Link]
like [Link]() or for server-side errors (e.g.,
[Link](), which also 404 Not Found, 500
return Promises. Internal Server Error).
Example

fetch("[Link]
.then(response => [Link]())
.then(data => [Link](data))
.catch(error => [Link](error));

With async/await

async function getPost() {


try {
const res = await fetch("[Link]
const data = await [Link]();
[Link](data);
} catch (err) {
[Link](err);
} }
getPost();
<!DOCTYPE html>
<html>
<head>
<title>Book Store - AJAX</title> </head>
<body>
<h2>Book List (AJAX)</h2>
<button onclick="getBooks()">Load Books</button>
<ul id="bookList"></ul>
<script>
function getBooks() {
const xhr = new XMLHttpRequest();
[Link]("GET", "[Link] true);
[Link] = function () {
if ([Link] === 200) {
const books = [Link]([Link]);
let output = "";
[Link](book => {
output += `<li>${[Link]} - ${[Link]}</li>`; });
[Link]("bookList").innerHTML = output;
} };
[Link](); }
</script> </body> </html>
UsingFetch API

Product List (Fetch


API)
Load Books
// CREATE a new product (POST)
const newProduct = { name: "Laptop", price: 800 };

fetch("[Link] {
method: "POST",
headers: {
"Content-Type": "application/json" // we are sending JSON data
},
body: [Link](newProduct) // convert JS object to JSON string
})
.then(response => [Link]()) // convert response to JS object
.then(data => {
[Link]("✅ Congrats! Product added:", data);
})
.catch(error => [Link]("❌ Product not added:", error));
// UPDATE an existing product (PUT)
const updatedProduct = { name: "New Laptop", price: 900 };
const productId = "1"; // ID of the product to update

fetch(`[Link] {
method: "PUT",
headers: {
"Content-Type": "application/json"
},
body: [Link](updatedProduct)
})
.then(response => [Link]())
.then(data => [Link]("✅ Product updated:", data))
.catch(error => [Link]("❌ Error updating product:", error));
// DELETE a product (DELETE)
const productIdToDelete = "1"; // ID of the product to delete

fetch(`[Link] {
method: "DELETE"
})
.then(response => [Link]())
.then(data => [Link](" ️ Product deleted:", data))
.catch(error => [Link]("❌ Error deleting product:", error));

// READ (GET) - Fetch list of all products


fetch("[Link]
.then(response => [Link]())
.then(data => {
[Link]("📦 Products Output:", data);
})
.catch(error => [Link]("❌ No Data Found:", error));

You might also like