0% found this document useful (0 votes)
6 views57 pages

Lec 7-Web API

The document outlines the fundamentals of Web APIs, including their definition, types, and importance in modern web applications. It covers key concepts such as JSON structure, REST principles, and methods for handling API requests using Fetch and Axios. Additionally, it discusses debugging common API errors and provides an overview of HTTP status codes and CORS mechanisms.
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)
6 views57 pages

Lec 7-Web API

The document outlines the fundamentals of Web APIs, including their definition, types, and importance in modern web applications. It covers key concepts such as JSON structure, REST principles, and methods for handling API requests using Fetch and Axios. Additionally, it discusses debugging common API errors and provides an overview of HTTP status codes and CORS mechanisms.
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

WEB API

1
Learning Outcomes

• Explain what an API is and how it works in modern web


applications.
• Describe JSON structure and use it to exchange data.
• Understand REST principles
• Send and handle API requests using Fetch and Axios.
• Use Promises and async/await to manage asynchronous
operations.
• Build simple client–server interactions (consuming public
APIs).
• Debug and troubleshoot common API call errors (CORS,
network, status codes).

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

2
Content

1. Web API Fundamentals


2. Fetch API
3. Axios Library
4. Asynchronous JavaScript

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

3
1. Web API Fundamentals
1.1. API
1.2. JSON
1.3. REST

4
1.1. API

• An API (application programming interface) is a set of


rules or protocols that enables software applications to
communicate with each other.
• An API is like a restaurant waiter — you tell the waiter
what you want, the waiter communicates with the
kitchen, and brings the result back to you.

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

5
Why Do We Need APIs?

• Modularity
• breaks large, complex systems into smaller,
independent services
• enables easier maintenance, faster development, and
better scalability.
• Security (Access Control):
• exposes only the necessary endpoints and actions
• protects sensitive data from unauthorized access
• Interoperability (Integration):
• provides a communication standard for different
technologies and systems
• allows systems to integrate easily with each other.

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

6
Main Types of APIs

• 1. Web APIs (most common)


• Used by browsers, mobile apps, servers
• Use HTTP/HTTPS
• 2. Library APIs
• Function calls inside programming languages
• Example: DOM API, [Link] API
• 3. Operating System APIs
• Windows API, macOS API
• 4. Third-party Service APIs
• Google API, OpenAI API, Stripe API, Firebase API
• 5. Internal/Private APIs
• Used inside organizations for internal systems
TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG
School of Information and Communication Technology

7
Real-World Examples of APIs

• Daily Apps
• Google Maps API → show maps inside mobile apps
• YouTube API → embedd video, search results
• Gmail API → send email
• Facebook API → login with Facebook
• Message API → send message
• Weather API → display current weather
• Finance
• VNPay API, Momo API, ZaloPay API → payment
• Striple API, PayPal API → payment
• E-commerce
• Tiki Open API → product, order
• Amazon API → product, order

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

8
4 Core Components of a Web API

Component Meaning Purpose

URL Resource address Identify target

Method Action type Define operation

Context, auth,
Headers Metadata
format

Body Data payload Send content

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

9
How Web APIs Work (Simple Flow)

• APIs act as a communication bridge between a client


(your app, browser, or system) and a server (the
backend that stores data or performs actions).
• Flow
• 1. Client sends a Request via the API
• 2. API receives the Request
• 3. Server processes the Request
• 4. API returns a Response

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

10
Inspecting Web APIs with DevTools
• Open DevTools
• Choose Inspect
• Choose Tab Network
• Filter Request
• XHR: AJAX/Fetch/Axios
• Doc/JS/CSS/Img
• Inspect a Request
• Response body
• Status code
• Response header
• [Link]
[Link]/posts

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

11
1.2. JSON

• JSON (JavaScript Object Notation) is a lightweight,


text-based data format used to store and exchange
data between systems.
• Features
• Human-readable
• Easy for machines to parse
• Language-independent
• Structure
• Objects (key-value pairs)
• Arrays (ordered lists)
• Note
• No comments allowed
• UTF-8 by default
TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG
School of Information and Communication Technology

12
JSON Structure: Object & Array

• Two main structures


• Objects → key–value pairs
• Arrays → an ordered list of values
• JSON Object: collection of key–value pairs enclosed in { }
• Format: "key": value
• Keys are always strings
• Values can be any JSON data type
• Key–value pairs are separated by commas
• Unordered

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

13
JSON Structure: Object & Array

• JSON Array: an ordered list of values enclosed in [ ]


• Ordered (index start at 0)
• Used for lists: items, users, posts, etc

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

14
JSON JavaScript: parse() and stringify()

• Server sends JSON to Client => converts JSON to JS object


• Client sends data to Server => converts JS object to JSON
• [Link](): converts JSON string → JS object
• const json = '{"name": "Alice"}';
• const obj = [Link](json);
• [Link]([Link]); // "Alice”

• [Link](): converts JS object → JSON String


• const user = {name: "Alice"};
• const jsonString = [Link](user);
• [Link](jsonString); //‘{"name": "Alice"}'

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

15
JSON Nested

• Nested JSON
• Objects contain objects
• Objects contain arrays
• Arrays contain objects

• Example
• [Link];
// "Hanoi"
• [Link][0].items[1]
.price; // 20

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

16
JSON Problems

• JSON
• supports: String, Number, Boolean, Null, Object, Array
• not support: Date, Function, undefined, binary data,
regular experssion, NaN

• Date → JSON → Date


• const obj = {created: new Date() };
• [Link](obj);
//{ "created": "2025-10-10T05:00:00.000Z" }
• const data = [Link](json);
• [Link] = new Date([Link]);
• [Link]({ x: undefined }); // "{}”
• [Link]({ fn: () => {} });// "{}"
TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG
School of Information and Communication Technology

17
1.3. REST

• REST = Representational State Transfer: is a set of


principles used to design Web APIs.
• Restful API: is an API that follows REST principles

Principle Meaning
Client–Server UI separate from backend
Stateless No session on server
Cacheable Responses can be cached
Uniform Interface Consistent API design
Layered System Multiple transparent layers
Code on Demand Server sends code (optional)
TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG
School of Information and Communication Technology

18
REST: Resource Naming Rules

• Resource: any entity


• Use nouns, not a verb, e.g., users, orders, posts
• Good: /users, /orders/123
• Bad: /user, /getUsers, /createOrder
• Use hierarchical structure:
• /users/10/orders
• /orders/5/items
• Use Path for Resources, Query for Filters
• /products → all products
• /products?category=phone → filtered list
• Use Lowercase & Hyphens: /user-profiles
• Avoid Trailing Slashes: /users insted of /users/
TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG
School of Information and Communication Technology

19
CRUD Mapping

CRUD HTTP Method Example Description

Create POST /users Create new user

Read GET /users/5 Retrieve user

PUT /users/5 Replace entire user


Update
PATCH /users/5 Update partitally

Delete DELETE /users/5 Delete user

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

20
Parameters: Identifier (Path) vs Filter (Query)

• Path Parameters = Identifier


• represent a specific resource
• identify resource by ID/code
• order is important
• GET /users/10
• GET /orders/A001/items/5

• Query Parameters = Filters/Sorting/Pagination


• use for query (e.g., filtering, sorting, pagination)
• order doesn’t matter
• GET /products?category=phone
• GET /posts?sort=desc&page=2&limit=10
• /products/category/phone (not
RESTful)
TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG
School of Information and Communication Technology

21
HTTP Status Code

Category Meaning Examples

1xx Info 100

2xx Success 200, 201, 204

3xx Redirect 301, 302, 304

4xx Client error 400, 401, 403, 404

5xx Server error 500, 502, 503, 504

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

22
2xx Success Codes (200, 201, 204)

• 200 OK
• Request succeeded and returns a response body.
• Return JSON data
• e.g., GET /users
• 201 Created
• A new resource was successfully created
• May return newly created object
• e.g., POST /users (create user)
• 204 No Content
• Request succeeded but no response body
• e.g., DELETE /users/10

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

23
4xx Client Errors (400, 401, 403, 404)

• 400 — Bad Request


• server cannot process the request because of invalid request
• e.g., POST /users with missing "name" field
• 401 - Unauthorized
• authentication is required but missing or invalid.
• e.g, GET /users without JWT token
• 403 — Forbidden
• Client is authenticated but not allowed to access
• e.g., insufficient permissions
• 404 — Not Found
• requested resource does not exist
• e.g., wrong path, resource not found
TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG
School of Information and Communication Technology

24
5xx Server Errors (500, 503)

• 500 — Internal Server Error


• server itself encountered an error.
• e.g., backend bugs, database errors, exception
• 503 — Service Unavailable
• server is reachable, but temporarily unable to handle the
request.
• e.g., server overload
• 502 — Bad Gateway (Gateway: Nginx, load balancer)
• gateway received a bad response from server.
• e.g, server returned invalid response
• 504 — Gateway Timeout
• gateway did not receive a response in time from server
• e.g., slow backend processing
TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG
School of Information and Communication Technology

25
Gateway (Nginx, Apache, AWS, Azure...)

• Gateway is the smart middle layer that controls how the


Client communicates with the Server
• protect backend server
• filter requrest, block attacks
• direct traffics
• track errors

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

26
CORS: When the Browser “Asks Permission”

• CORS is a security mechanism in browsers that controls whether a


web page can call APIs from a different origin.
• Origin = protocol + domain + port
• e.g., [Link] and [Link] are different origins
• Browser sends Preflight request for non-simple requests (e.g.,
DELETE, PUT, PATCH)
• OPTIONS /api HTTP/1.1
• Origin: [Link]
• Server must reply as follows to allow browser to call API
• HTTP/1.1 204 No Content
• Access-Control-Allow-Origin: [Link]
• Access-Control-Allow-Methods: GET, POST, PUT
• Access-Control-Allow-Headers: Content-Type
TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG
School of Information and Communication Technology

27
Simple vs Non-Simple Requests

• Simple requests: three conditions


1. Allowed Methods: GET, POST, HEAD
2. Allowed Headers (Only simple headers)
• Accept
• Accept-Language
• Content-Language
• Content-Type (but only 3 specific types below)
3. Content-Type must be one of:
• text/plain
• multipart/form-data
• application/x-www-form-urlencoded
Browser sends the request immediately (no OPTIONS).
TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG
School of Information and Communication Technology

28
2. Fetch API

29
Introduction

• A modern interface for fetching resources


• Native in all modern browsers
• Advantages
• simplicity and modernity (promise-based)
• clear request/response objects for data handling
• excellent JSON handling
• Disadvantages
• Error handing complexity (manual status check)
• Lack of timeout mechanism
• Manual cookie and credentials handing

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

30
Fetch API: Syntax with Async Await

• Writes code like traditional synchronous (blocking) code.


• async: declares an asynchronous function
• await: pauses the execution of the async function
until the Promise settles
• Two-step process for data access
• fetch(): return a response object
• [Link]() or [Link] to access the data

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

31
Handling Response

• fetch() considers a successful HTTP response to be any


response received from the server, including 404 (Not
Found), 500 (Internal Server Error).

• Developers must manually check the HTTP status code


• [Link]: number, e.g., 200, 404
• [Link]: string, e.g., OK, Not Found
• [Link]: boolean
• True if the status code is in the range 200-299;
• False otherwise -> Error handling

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

32
[Link]

• A method of the Fetch Response object


• Reads the response body
• Parses it as JSON
• Returns a Promise that resolves to a JavaScript object
• Notes
• Works only if the response body is valid JSON
• Non-JSON data, use: [Link](), [Link](),
[Link]()

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

33
Fetch - GET

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

34
Fetch - POST

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

35
Authorization Token (Bearer)
• Client sends a token in the Authorization header:
• Authorization: Bearer <token> → browser sends a Preflight

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

36
Timeout with [Link]()
• Fetch API has no built-in timeout.
• If the server hangs, the request waits forever
• [Link](): runs two promises in parallel i.e.,
Fetch and Timeout

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

37
AbortController: Active Request Cancellation

• A browser API that allows


you to cancel (abort) an
ongoing Fetch request.
• Useful for stopping slow,
unnecessary, or
duplicated requests.
• Does AbortController
cancel the Promise?

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

38
3. Axios Library

39
Introduction

• Axios is one of the most widely HTTP client libraries.


• Automatic Error Handling
• automatically rejects promises for all HTTP errors
• [Link]("/api/users")
.catch(err => [Link]("Error:", err));
• Built-in Timeout, Cancelation
• Easy timeout configuration (no need AbortController).
• [Link](url, { timeout: 5000 });
• Automatic JSON Handling & Safer Defaults
• Automatically parses JSON into [Link]
• const res=await [Link](url,{title: ”A”});
• [Link]([Link]);

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

40
Axios vs Fetch

• Use Axios for: large apps, interceptors, timeouts, clean error


handling.
• Use Fetch for: simple requests, modern browsers,
lightweight usage without libraries.
• Axios
• Better error handling (treats non-2xx as errors)
• Has built-in timeout
• Cleaner syntax for complex calls
• Fetch
• Native browser API (no installation)
• No built-in timeout
• Requires manual JSON parsing
• Treats non-2xx responses as success (must check [Link])
TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG
School of Information and Communication Technology

41
Install Axios

• Install
• Project: npm install axios
• Browser via CDN:
<script
src="[Link]
[Link]">
</script>
• Quick check
• import axios from "axios";
• [Link]("/api/test")
.then(res => [Link]("Axios Ready:",
[Link]));

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

42
Axios GET: Clean Syntax & Destructuring
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Axios GET Demo</title>
<script
src="[Link]
[Link]">
</script>
</head>
<body>
<h2>Axios GET Demo</h2>
<pre id="output"></pre>
<script>
[Link]("[Link]
om/users")
.then(response => {
[Link]("output").textContent
= [Link]([Link], null, 2);
})
.catch(err => [Link](err));
</script>
</body>
</html>

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

43
Axios POST/PUT/DELETE

POST (create data)

PUT (update entire data)

DELETE (remove data)

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

44
Axios Instance: Global Configuration

• A pre-configured Axios object contains shared settings


(base URL, headers, timeout, interceptors).
• Allow reuse it across your entire application

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

45
Axios - Demo

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

46
Request Interceptor

• allows you to run code BEFORE every request is sent.


• add headers
• inject Authorization tokens
• log request information

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

47
Response Interceptor
• allows you to handle response and error BEFORE
conducting application logic.
• handle API errors
• auto-refresh tokens
• standardize error messages
• ...

Catch all errors from every


request in one place.
No need to write try/catch
everywhere.

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

48
Axios Error Handling

• When Axios receives an HTTP error (4xx / 5xx), it


returns an Error Object.
• [Link]: HTTP status code, e.g., 400,
401, 403, 404, 500
• [Link]: error body from the server
• [Link]: headers from the server
• [Link]: request configuration

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

49
Canceling Requests

• use AbortController

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

50
Retry Pattern: Automatic Retries on 503/429

• When to Retry
• 503 Service Unavailable → server is overloaded or
restarting
• 429 Too Many Requests → hit rate limit, need to
slow down

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

51
4. Asynchronous JavaScript

52
async/await

• async makes a function return a Promise


• await pauses execution until the Promise resolves/rejects

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

53
[Link]: Boost Performance with Parallel Requests

• [Link]() allows you to run multiple asynchronous


operations in parallel
• Total time = time of the slowest request
const [users, posts] = await
[Link]([
[Link]("/users"),
[Link]("/posts")
]);
• If any Promise fails:
• [Link]() rejects immediately
• All results are discarded
• Error goes to catch
TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG
School of Information and Communication Technology

54
[Link]: Safe Parallel Execution

• Runs multiple promises in parallel and waits for all of


them to finish, regardless of success or failure
• Ideal when you need all results, even failed ones

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

55
Exercise

Build a CRUD web application using Fetch or Axios to interact


with [Link]
Required Features:
• Read: show a table of users with name, email, phone
• Create: form to add new user
• Update/Edit: edit or popup form
• Delete: remove user from table
• Search: filter users by name
• Pagination (optional)
• Note:
• use async/await, not .then()
• update UI after POST/PUT/DELETE
• handle errors
TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG
School of Information and Communication Technology

56
TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG
School of Information and Communication Technology

57

You might also like