Understanding APIs: A Beginner's Guide to Web APIs
If you're learning web development, you've probably seen code like this:
fetch("/api/users")
But what actually happens when this code runs?
How does a React application communicate with a backend? What is a REST API? What are endpoints, HTTP methods, JSON, status codes, and authentication?
In this guide, we'll break down the fundamentals of APIs and see how they are used in real-world web applications.
What Is an API?
API stands for Application Programming Interface.
Simply put, an API allows different software applications to communicate with each other.
In modern web applications, a frontend usually doesn't communicate directly with a database. Instead, it sends requests to a backend through an API.
A typical flow looks like this:
Frontend
↓
API Request
↓
Backend Server
↓
Database
↓
Backend Server
↓
API Response
↓
Frontend
For example, when you search for restaurants in a food delivery application, the frontend can send a request to a backend API. The backend processes the request, retrieves the required information, and returns a response.
The frontend can then display that information to the user.
Why Do We Use APIs?
Imagine you're building an employee management application.
The application might need to:
- Get employee details
- Add a new employee
- Update employee information
- Delete employees
- Search for employees
Instead of allowing the frontend to directly access the database, we can create APIs for these operations.
For example:
GET /api/employees
POST /api/employees
PUT /api/employees/101
DELETE /api/employees/101
This separation provides several benefits:
- Better separation between frontend and backend
- Improved security
- Easier maintenance
- Reusable backend services
- Support for multiple clients
- Easier integration with third-party services
What Is a REST API?
One of the most common approaches to building web APIs is REST.
REST stands for Representational State Transfer.
REST APIs commonly use HTTP methods to perform operations on resources.
For example, suppose employees is a resource.
We might have:
GET /api/employees
GET /api/employees/101
POST /api/employees
PUT /api/employees/101
DELETE /api/employees/101
Each HTTP method represents a different operation.
Let's look at them one by one.
HTTP Methods
- GET
GET is used to retrieve data.
fetch("/api/employees")
.then(response => response.json())
.then(data => console.log(data));
This request asks the server to return employee information.
- POST
POST is commonly used to create new data.
fetch("/api/employees", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
name: "John",
role: "Developer"
})
});
Here, the frontend sends employee information to the backend.
The backend can validate the data and store it in the database.
- PUT
PUT is generally used to update an existing resource.
fetch("/api/employees/101", {
method: "PUT",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
name: "John",
role: "Senior Developer"
})
});
This request updates employee 101.
- DELETE
DELETE is used to remove a resource.
fetch("/api/employees/101", {
method: "DELETE"
});
This tells the backend to delete employee 101.
What Is an API Endpoint?
An API endpoint is a specific URL through which a client accesses a resource or functionality.
For example:
GET /api/products
This could return a list of products.
To retrieve a specific product:
GET /api/products/25
A typical endpoint can be understood as:
Base URL + API Path + Resource + Identifier
For example:
https://example.com/api/products/25
Here:
https://example.com → Base URL
/api → API path
/products → Resource
/25 → Resource ID
API Requests and Responses
API communication involves two important things:
Request → Client sends data to the server
Response → Server sends data back to the client
For example, a client might send:
{
"name": "John",
"email": "john@example.com"
}
The backend processes the request and might return:
{
"success": true,
"message": "Employee created successfully",
"employeeId": 101
}
The frontend can then use the response to update the UI.
What Is JSON?
JSON, or JavaScript Object Notation, is one of the most common formats used to exchange data through APIs.
For example:
{
"id": 101,
"name": "John",
"role": "Developer",
"experience": 3
}
JSON is popular because it is:
- Easy to read
- Lightweight
- Easy to process
- Supported by many programming languages
- Commonly used with REST APIs
If you're working with JavaScript, you'll encounter JSON constantly.
HTTP Status Codes
APIs use HTTP status codes to tell the client what happened after processing a request.
Some common status codes are:
| Status Code | Meaning |
|---|---|
200 |
OK |
201 |
Created |
400 |
Bad Request |
401 |
Unauthorized |
404 |
Not Found |
500 |
Internal Server Error |
For example:
200 OK
means the request was successful.
While:
404 Not Found
means the requested resource could not be found.
Understanding these codes is extremely useful when debugging API problems.
API Authentication
Not every API endpoint should be publicly accessible.
For example, an employee management system shouldn't allow anyone to access employee data.
This is where authentication comes in.
Authentication verifies the identity of the person or application making the request.
After login, a backend may generate an authentication token.
The client can then send the token with future requests:
Authorization: Bearer <token>
The backend verifies the token before allowing access to protected resources.
Authentication is commonly used in:
- Banking applications
- E-commerce applications
- Social media applications
- Admin dashboards
- Employee management systems
- Payment applications
Using APIs in React
React applications frequently communicate with APIs.
Here's a simple example:
import { useEffect, useState } from "react";
function Employees() {
const [employees, setEmployees] = useState([]);
useEffect(() => {
fetch("/api/employees")
.then(response => response.json())
.then(data => setEmployees(data));
}, []);
return (
<div>
{employees.map(employee => (
<p key={employee.id}>{employee.name}</p>
))}
</div>
);
}
Let's break down what happens:
- React renders the component.
-
useEffect()runs. -
fetch()sends an API request. - The server returns employee data.
-
setEmployees()stores the response. - React renders the employee names.
This is one of the most common patterns you'll see when building React applications that consume APIs.
Building an API with Node.js and Express
APIs can be created using many backend technologies.
In the JavaScript ecosystem, Node.js and Express.js are commonly used to build APIs.
Here's a simple example:
const express = require("express");
const app = express();
app.use(express.json());
app.get("/api/employees", (req, res) => {
res.json([
{
id: 1,
name: "John",
role: "Developer"
}
]);
});
app.listen(5000, () => {
console.log("Server running on port 5000");
});
What's happening here?
- Express creates the backend server.
-
/api/employeesis the endpoint. -
GEThandles requests to that endpoint. -
res.json()sends JSON data to the client. - The server listens on port
5000.
Now a frontend application can request:
GET /api/employees
and receive the employee data.
A Real-World Example
Let's look at an online shopping application.
When the user opens the products page, the frontend might send:
GET /api/products
The backend retrieves products from the database and returns:
[
{
"id": 1,
"name": "Laptop",
"price": 65000
},
{
"id": 2,
"name": "Mobile Phone",
"price": 25000
}
]
The frontend displays these products.
When the user places an order:
POST /api/orders
The backend processes the order and stores it in the database.
The complete flow is:
User
↓
React Frontend
↓
API Request
↓
Node.js / Express
↓
Database
↓
API Response
↓
React Frontend
↓
User
This simple architecture is behind many real-world web applications.
API Security Best Practices
When building APIs, security should always be considered.
Some important practices include:
- Validate user input
- Use authentication and authorization
- Protect sensitive information
- Use HTTPS
- Handle errors properly
- Never expose database credentials
- Implement appropriate access controls
- Use meaningful HTTP status codes
- Validate data on the backend
One important rule is:
Never rely only on frontend validation.
Frontend validation improves the user experience, but users can send API requests directly without using your frontend.
That's why backend validation is essential.
Where Are APIs Used?
APIs are not limited to web applications.
They're used throughout modern software development.
Web Applications
React, Angular, and Vue applications communicate with backend APIs.
Backend Applications
Node.js, Java Spring Boot, Python, and other technologies can create and consume APIs.
Mobile Applications
Android and iOS applications communicate with backend servers through APIs.
Third-Party Services
Applications can integrate with external services such as:
- Payment systems
- Maps
- Email services
- Authentication providers
- Cloud platforms
- Other software platforms
APIs make these integrations possible.
The Big Picture
If you're new to APIs, remember this simple model:
CLIENT
↓
REQUEST
↓
API
↓
BACKEND
↓
DATABASE
↓
BACKEND
↓
RESPONSE
↓
CLIENT
The frontend doesn't need to know how the database works internally.
It needs to know how to communicate with the API:
- Which endpoint to call
- Which HTTP method to use
- What data to send
- How to authenticate
- How to handle the response
That's the power of an API.
Final Thoughts
APIs are one of the most important concepts to understand when learning modern web development.
Once you understand:
- REST APIs
- HTTP methods
- Endpoints
- Requests and responses
- JSON
- Status codes
- Authentication
- API security
technologies like React, Node.js, Express, and databases become much easier to connect together.
But don't stop at reading.
Build an API.
Create a small Express server. Add a few endpoints. Connect it to a React application. Send requests. Inspect the responses. Handle errors.
That's when the theory starts becoming real.
If you're learning web development, APIs are a skill worth mastering.
Keep building. Keep experimenting. 🚀
Top comments (0)