Learn what an API is, how requests and responses work, and how to use a simple API with JavaScript.
Introduction
Have you ever logged into a website using Google, checked the weather in an app, or paid online?
Have you wondered how different applications communicate with each other?
For example, when you open a weather app, it displays information such as temperature, humidity, and wind speed. But does the app collect all this weather information itself?
Usually, no. It requests the information from another service.
This communication often happens through an API.
APIs are used in web development, mobile applications, payment systems, AI applications, and many other types of software.
In this beginner-friendly guide, we'll understand what an API is, how it works, and how to make a simple API request using JavaScript.
1. What Is an API?
API stands for Application Programming Interface.
In simple terms, an API is an interface that allows one software application to interact with another software system through defined rules.
Imagine you're in a restaurant.
- You are the customer who wants to order food.
- The kitchen prepares the food.
- The waiter takes your order to the kitchen and brings back the result.
You don't need to enter the kitchen or understand how every dish is prepared. You communicate through the waiter.
An API works in a similar way.
- Client: The application requesting information.
- API: The interface through which the request is made.
- Server: The system that processes the request.
- Response: The information or result returned to the client.
For example, a frontend application can request a list of products from a backend API without directly accessing the backend's database.
2. Why Do Applications Need APIs?
Imagine you're building an online shopping application.
Your application needs to:
- Display products.
- Register users.
- Process payments.
- Track orders.
- Send notifications.
You could build all these capabilities yourself, but many services already provide APIs for specific tasks.
For example:
- A payment provider can expose an API for processing payments.
- A mapping service can expose an API for location and directions.
- A weather service can expose an API for weather information.
- Your own backend can expose APIs for users, products, and orders.
APIs make it possible for software systems to communicate without needing to know every internal implementation detail of each other.
3. How Does an API Work?
Let's understand the basic flow.
flowchart TD
A["User"] --> B["Frontend Application"]
B --> C["API Request"]
C --> D["Backend Server"]
D --> E["Process Request"]
E --> F["Database, if needed"]
F --> E
E --> G["API Response"]
G --> B
B --> H["Display Result"]
Here's what happens:
Step 1: The user performs an action.
For example, the user opens a product page.
Step 2: The frontend sends a request.
The browser sends an HTTP request to an API endpoint.
Step 3: The backend processes the request.
The server checks the request, applies business rules, and may retrieve information from a database.
Step 4: The server returns a response.
The response may contain product information, an error message, or another result.
Step 5: The frontend uses the response.
The application displays the products or informs the user if something went wrong.
One important detail: not every API request needs a database query. Some APIs calculate results, call other services, or return information directly.
4. What Is an API Endpoint?
An API endpoint is a particular URL through which an API exposes a resource or operation.
For example:
GET /api/products
GET /api/products/101
POST /api/products
These examples describe different operations:
-
GET /api/products— retrieve a list of products. -
GET /api/products/101— retrieve a particular product. -
POST /api/products— request the creation of a product.
These are illustrative routes. The exact behavior depends on how the API is designed.
A complete API URL might look like this:
https://api.example.com/products
Here:
-
httpsis the protocol. -
api.example.comis the host. -
/productsis the endpoint path.
The HTTP method helps specify what operation the client wants to perform.
5. What Are HTTP Methods?
HTTP methods describe the intended action for a request.
| Method | Common purpose | Example |
|---|---|---|
GET |
Retrieve information | Get a product list |
POST |
Submit data or create a resource | Create an order |
PUT |
Replace a resource | Replace a product record |
PATCH |
Partially update a resource | Change a product price |
DELETE |
Delete a resource | Delete a product |
The actual behavior depends on the API's design.
For example, when a user submits a registration form, the frontend might send a POST request containing the user's details to a registration endpoint.
6. What Is JSON in an API?
JSON stands for JavaScript Object Notation.
It is a common data format used to exchange information between applications.
For example, an API might return this product:
{
"id": 101,
"name": "Wireless Mouse",
"price": 799,
"inStock": true
}
This response contains:
-
id: a product identifier. -
name: the product name. -
price: the price. -
inStock: whether the product is available.
The frontend can read this JSON and display the product information.
JSON is widely used because it is lightweight, readable, and supported by many programming languages.
7. Let's Make Our First API Request
Now let's use JavaScript to call a public test API.
We'll use JSONPlaceholder, a service designed for testing and learning.
Example endpoint:
https://jsonplaceholder.typicode.com/posts/1
Open the URL in your browser to see a sample JSON response.
Example using JavaScript
async function getPost() {
try {
const response = await fetch(
"https://jsonplaceholder.typicode.com/posts/1"
);
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
const data = await response.json();
console.log("Post title:", data.title);
console.log("Post body:", data.body);
} catch (error) {
console.error("Failed to fetch post:", error.message);
}
}
getPost();
What does this code do?
1. fetch()
Sends an HTTP request to the API endpoint.
2. await response
Waits for the HTTP response before continuing.
3. response.ok
Checks whether the HTTP status indicates success, generally a status in the 200–299 range.
4. response.json()
Reads and parses the response body as JSON.
5. console.log()
Prints the retrieved data in the console.
6. try...catch
Handles errors that may occur during the request or response processing.
When the request succeeds, you'll see the post's title and body in the console.
This example uses a public testing service. Real APIs may require authentication, have rate limits, or enforce other access restrictions.
8. What Are API Status Codes?
An API response usually includes an HTTP status code that indicates the outcome of the request.
Here are some common examples:
| Status code | Meaning |
|---|---|
200 OK |
The request succeeded |
201 Created |
A resource was created successfully |
400 Bad Request |
The request contains invalid data or syntax |
401 Unauthorized |
Valid authentication credentials are missing or invalid |
403 Forbidden |
The client is not allowed to perform the operation |
404 Not Found |
The requested resource was not found |
500 Internal Server Error |
The server encountered an unexpected problem |
Understanding status codes makes debugging API issues much easier.
For example, a 404 response may mean that the endpoint URL is incorrect or the requested resource doesn't exist.
A 401 response may mean that the request needs valid authentication credentials.
Always check the API's documentation because the exact error details and behavior vary between services.
9. What Is the Difference Between a Frontend, Backend, and API?
These terms are related, but they are not the same.
Frontend
The part of an application that users interact with, such as buttons, forms, and product pages.
Common technologies include HTML, CSS, JavaScript, and React.
Backend
The server-side application that handles business logic, validation, permissions, and data processing.
Common technologies include Python, Node.js, Java, and other server-side
Top comments (0)