Lesson 1: Build and test RESTful APIs with Postman
RESTful APIs
1. What is a RESTful API?
Definition: REST (Representational State Transfer) is an architectural style for designing networked applications. A RESTful API allows interaction with web services using standard HTTP methods (GET, POST, PUT, DELETE).
Key Concepts and RESTful API Charateristics:
Client-Server: The client (e.g., a web browser, mobile app) and server are separate entities.
Stateless: Each request from a client contains all the information needed to process it.
Cacheable: Responses can be cached to improve performance.
Resources: Represented as URLs (e.g.,
/users
,/products
).Uniform Interface: A consistent way of interacting with resources using HTTP Methods, URLs, and data formats (typically JSON). :
GET: Retrieve data.
POST: Create new data.
PUT: Update existing data.
DELETE: Remove data.
URLs (Endpoints): Unique addresses used to identify resources.
Representations: Resources are transferred in a specific format, most commonly JSON (JavaScript Object Notation).
Example: A RESTful API for a bookstore might have endpoints like
/books
to get a list of books or/books/:id
to get details of a specific book.
2. Building RESTful APIs with Express Framework and a Vite React Application:
Setting up the Project:
Create a Vite React project:
Bash
Install Express and other dependencies:
Setup Express and Testing APIs:
Initialize a Node.js Project:
Create the server file (
server.js
orindex.js
):Create
index.js
:
Testing RESTful APIs with Postman:
Testing Steps:
GET Request:
Open Postman and enter
http://localhost:3000/books
.Click Send to retrieve the list of books.
POST Request:
Select POST and enter
http://localhost:3000/books
.Go to Body, select raw, and choose JSON format.
Enter the following:
Click Send to add a new book.
PUT Request:
Select PUT and enter
http://localhost:3000/books/1
.Update the book information in the Body and click Send.
DELETE Request:
Select DELETE and enter
http://localhost:3000/books/1
.Click Send to delete the book.
4. Integrating the API with a Vite React Application:
Fetching Data from API:
Edit
src/App.jsx
:
Run both the server and the React app:
In your terminal, navigate to your project directory and run:
node index.js
(ornodemon index.js
for automatic restarts).In a separate terminal, run:
npm run dev
(oryarn dev
) to start your React development server.
Student Activity:
Build a RESTful API using Express to manage a list of tasks.
Test the API using Postman (add, update, delete tasks).
Create a Vite React app to display and interact with the API.
By the end of this session, students will understand RESTful APIs, how to build them using Express, and how to test and integrate them into a React application.
Last updated