Chapter 4: APIs (REST & GraphQL)
The Frontend (React) and the Backend (Node/Python/Database) are completely separate entities. They do not know about each other. To make them communicate, you must build a bridge. That bridge is an API (Application Programming Interface).
REST APIs: The Industry Standard
REST (Representational State Transfer) is a set of rules for building APIs. A RESTful API relies on standard HTTP Methods to perform CRUD (Create, Read, Update, Delete) operations on a database.
- GET
/api/users- Retrieve a list of all users. - POST
/api/users- Create a new user (data sent in the body). - PUT
/api/users/5- Update the data of User ID 5. - DELETE
/api/users/5- Delete User ID 5.
// The Backend returning JSON via a REST API
{
"status": 200,
"data": {
"id": 5,
"username": "msmaxpro",
"role": "admin"
}
}
Status Codes Matter
When a frontend client sends an API request, your backend must respond with the correct HTTP Status Code. If you send a `200 OK` code when an error occurred, the frontend code will break.
- 200s: Success (200 OK, 201 Created)
- 400s: Client Error (400 Bad Request, 401 Unauthorized, 404 Not Found)
- 500s: Server Error (500 Internal Server Error)
GraphQL vs REST
REST is great, but sometimes it returns too much data. If the frontend only needs a user's name, a REST API might return the name, age, email, and address. GraphQL is a modern alternative created by Facebook where the frontend can request exactly the fields it wants, and nothing else. It prevents "over-fetching".
Mini Task: Use Postman
- Download Postman or use the browser version.
- Make a
GETrequest to a free public API (likehttps://pokeapi.co/api/v2/pokemon/ditto). - Inspect the JSON data that comes back. This is exactly what you will be building as a backend developer!