An API defines how software requests data or actions from another component. In this guide, a client calls GET /api/books and receives the book list as JSON.
1. What Is an API?
API stands for Application Programming Interface.
In simple terms, an API is a way for two software applications to communicate with each other.
An API defines how one application can request information or perform an action in another application.
Think about a restaurant.
You are a customer sitting at a table. You want to order food, but you cannot enter the kitchen and cook it yourself.
Instead, a waiter takes your order, sends it to the kitchen, and brings the prepared food back to your table.
In this example:
| Restaurant | Software |
|---|---|
| Customer | Client application |
| Waiter | API |
| Kitchen | Backend application |
| Food order | API request |
| Prepared food | API response |
The API acts as a communication interface between the client and the backend.
Real-world example: Weather application
Suppose you open a weather application and search for the temperature in Delhi.
The application does not necessarily have its own weather stations.
Instead, it may request weather information from a weather service through an API.
The communication looks like this:
User
|
v
Weather Application
|
| API Request
| City = Delhi
v
Weather Service API
|
| Retrieve Weather Data
v
Weather Database
|
| API Response
v
Weather Application
|
v
Temperature: 28°C
The temperature is an illustrative example, not live weather information.
The weather application only needs to know how to communicate with the service. It does not need access to the service's internal code or database.
Simple definition to remember
An API is a defined interface that allows software systems to exchange information or perform operations without exposing their internal implementation.
Not every API works over the internet. APIs also exist inside operating systems, programming libraries, and applications. In this article, we focus mainly on web APIs.
2. Why Do We Need APIs?
Without APIs, integrating multiple applications would be complicated.
Imagine building an e-commerce website.
Your website needs to:
- Register customers.
- Display products.
- Calculate delivery charges.
- Process payments.
- Track shipments.
- Send notifications.
You could build every feature yourself, but that would require substantial time, money, and infrastructure.
APIs allow your application to communicate with services that already provide these capabilities.
For example:
| Requirement | Possible API integration |
|---|---|
| Online payments | Razorpay, Stripe |
| Maps and locations | Google Maps |
| Weather information | Weather service API |
| Email notifications | SendGrid |
| SMS verification | Twilio |
| Customer authentication | OAuth-enabled identity provider |
| Shipment tracking | Logistics provider API |
| AI features | AI model provider API |
Major benefits of APIs
1. Reusability
The same API can be used by a website, mobile application, and other services.
2. Faster development
Developers can integrate existing functionality instead of rebuilding everything.
3. Security boundaries
A well-designed API can control which operations and data are available to callers.
4. Scalability
Independent services can be scaled according to demand.
5. Automation
Applications can exchange information without manual intervention.
6. Integration
APIs allow systems built using different programming languages and technologies to work together.
For example, a React application can communicate with a backend developed in Java, C#, Python, or Node.js through an HTTP API.
3. How Does an API Work?
To understand how a web API works, you need to understand three major components.
Client
The client is the application that sends a request.
Examples:
- Web browser
- Mobile application
- React frontend
- Another backend service
- API testing tool
API server
The API server receives requests, validates them, executes the required logic, and sends responses.
Database or external service
The backend may communicate with a database, another API, a message queue, or another system to process the request.
Example: Retrieve customer information
Suppose your application needs customer details for customer ID 101.
The client sends:
GET /api/customers/101 HTTP/1.1
Host: api.example.com
Accept: application/json
The API server processes the request and returns:
HTTP/1.1 200 OK
Content-Type: application/json
{
"id": 101,
"name": "Rahul Sharma",
"email": "rahul@example.com",
"city": "Delhi"
}
Complete API request lifecycle
1. User clicks "View Customer"
|
v
2. Frontend sends HTTP request
|
v
3. API server receives request
|
v
4. Authentication and validation
|
v
5. Execute business logic
|
v
6. Read information from database
|
v
7. Build API response
|
v
8. Frontend displays customer details
Important: The API does not necessarily communicate with a database. Some APIs calculate a result directly, use cached data, or call other services.
4. Understanding API Endpoints
An endpoint is a specific address through which a client can access an API operation or resource.
For example:
https://api.example.com/api/products
Let's break it down.
| Part | Value | Meaning |
|---|---|---|
| Protocol | https | Secure HTTP communication |
| Domain | api.example.com | API server address |
| Path | /api/products | Resource being accessed |
A single API service can expose many endpoints.
GET /api/products
GET /api/products/101
POST /api/products
PATCH /api/products/101
DELETE /api/products/101
Each combination of HTTP method and endpoint represents an operation.
For example:
GET /api/products retrieves products.
POST /api/products creates a product.
DELETE /api/products/101 deletes product 101.
The same URL can support different operations depending on the HTTP method.
5. HTTP Methods Explained
HTTP methods describe the action a client wants to perform.
The most common methods are GET, POST, PUT, PATCH, and DELETE.
| Method | Purpose | Example |
|---|---|---|
| GET | Retrieve data | Get all customers |
| POST | Submit data or create a resource | Create a customer |
| PUT | Create or replace a resource at a specified URI | Replace customer details |
| PATCH | Partially modify a resource | Update customer email |
| DELETE | Remove a resource | Delete a customer |
| HEAD | Retrieve response headers without a response body | Check resource metadata |
| OPTIONS | Discover supported communication options | CORS preflight |
GET: Retrieve information
GET /api/products
Example response:
[
{
"id": 1,
"name": "Laptop",
"price": 45000
},
{
"id": 2,
"name": "Keyboard",
"price": 1200
}
]
GET requests should not change server state as part of their intended operation.
POST: Create a resource
POST /api/products
Content-Type: application/json
Request body:
{
"name": "Mouse",
"price": 500
}
Example response:
{
"id": 3,
"name": "Mouse",
"price": 500
}
PUT: Replace a resource
PUT /api/products/3
Content-Type: application/json
{
"name": "Wireless Mouse",
"price": 800
}
PUT commonly replaces the entire resource representation, rather than only modifying specified fields.
PATCH: Partially update a resource
PATCH /api/products/3
Content-Type: application/json
{
"price": 750
}
Only the provided property is updated, according to the API's update rules.
DELETE: Remove a resource
DELETE /api/products/3
A successful deletion may return HTTP 204 No Content.
Expert tip: Idempotency
An operation is idempotent when repeating the same request has the same intended effect on server state as making it once.
GET, PUT, and DELETE are defined as idempotent HTTP methods.
POST is not automatically idempotent.
For example, sending the same payment creation request twice could create two payments unless the API has duplicate protection.
Payment APIs often use an idempotency key to prevent accidental duplicate operations.
6. Understanding HTTP Status Codes
Every HTTP response contains a status code indicating the outcome of the request.
Successful responses: 2xx
| Status | Meaning |
|---|---|
| 200 OK | Request completed successfully |
| 201 Created | Resource was successfully created |
| 202 Accepted | Request accepted for processing, not necessarily completed |
| 204 No Content | Request succeeded without a response body |
Client errors: 4xx
| Status | Meaning |
|---|---|
| 400 Bad Request | Invalid request |
| 401 Unauthorized | Authentication is missing or invalid |
| 403 Forbidden | Caller is not permitted to perform the action |
| 404 Not Found | Requested resource not found |
| 405 Method Not Allowed | HTTP method is not supported for the resource |
| 409 Conflict | Request conflicts with current resource state |
| 415 Unsupported Media Type | Request content type is unsupported |
| 422 Unprocessable Content | Request content cannot be processed under the applicable rules |
| 429 Too Many Requests | Rate limit exceeded |
Server errors: 5xx
| Status | Meaning |
|---|---|
| 500 Internal Server Error | Unexpected server error |
| 502 Bad Gateway | Gateway received an invalid upstream response |
| 503 Service Unavailable | Service temporarily unavailable |
| 504 Gateway Timeout | Gateway did not receive an upstream response in time |
Example error response
{
"error": {
"code": "PRODUCT_NOT_FOUND",
"message": "Product 101 was not found.",
"requestId": "req-7d32"
}
}
A good API uses meaningful status codes and consistent error responses.
Avoid returning HTTP 200 OK for every request and putting all errors inside the JSON response.
7. Understanding API Headers, Query Parameters, and Request Bodies
These are three important parts of API communication.
Request headers
Headers provide metadata about the request.
Example:
Content-Type: application/json
Accept: application/json
Authorization: Bearer YOUR_ACCESS_TOKEN
Common headers include:
| Header | Purpose |
|---|---|
| Content-Type | Format of the request body |
| Accept | Preferred response format |
| Authorization | Authentication credentials |
| X-Request-ID | Request tracking |
| If-Match | Conditional update |
| Idempotency-Key | Duplicate-operation protection when supported |
Query parameters
Query parameters allow clients to filter, sort, search, or paginate results.
Example:
GET /api/products?category=electronics&page=2&limit=10
Here:
category=electronicsfilters products.page=2requests the second page.limit=10requests up to ten products.
Path parameters
Path parameters identify a specific resource.
GET /api/products/101
Here, 101 is the product ID.
Request body
The request body contains information sent to the server.
Example:
{
"name": "Wireless Keyboard",
"price": 1599,
"category": "electronics"
}
JSON is widely used for HTTP APIs because it is readable and supported by most programming languages.
Other supported formats can include XML, form data, binary data, and protocol-specific encodings.
PART 2: DIFFERENT TYPES OF APIs
8. REST API
REST stands for Representational State Transfer.
REST is an architectural style for designing networked applications.
A RESTful API typically exposes resources through URLs and uses standard HTTP methods to operate on those resources.
Example:
GET /api/users
GET /api/users/10
POST /api/users
PUT /api/users/10
DELETE /api/users/10
REST principles
The REST architectural style includes several constraints:
Client-server separation: The client and server have independent responsibilities.
Stateless communication: Each request contains the information needed for the server to process it. Session context is not dependent on remembering previous requests.
Cacheability: Responses indicate whether and how they can be cached.
Uniform interface: Resources are accessed through a consistent set of interaction rules.
Layered system: Intermediaries such as gateways and proxies can exist between clients and servers.
Code on demand: An optional constraint that allows servers to provide executable code to clients.
JSON over HTTP is common for REST APIs, but REST does not require JSON.
9. SOAP API
SOAP stands for Simple Object Access Protocol.
SOAP is a messaging protocol commonly associated with XML and formal service contracts.
A SOAP request might look like:
<soap:Envelope
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<GetCustomer xmlns="http://example.com/customers">
<CustomerId>101</CustomerId>
</GetCustomer>
</soap:Body>
</soap:Envelope>
SOAP supports standards for features such as message security and reliable messaging.
It is still used in enterprise systems, financial services, and legacy integrations.
10. GraphQL API
GraphQL is a query language and runtime for APIs.
Instead of exposing many different REST endpoints, a GraphQL service commonly provides a single endpoint and allows clients to request specific fields.
Example:
query {
customer(id: "101") {
name
email
orders {
id
total
}
}
}
The response could look like:
{
"data": {
"customer": {
"name": "Rahul",
"email": "rahul@example.com",
"orders": [
{
"id": "5001",
"total": 1200
}
]
}
}
}
GraphQL is useful when clients need flexible access to related data.
However, complexity control, authorization, query limits, and caching require careful design.
11. gRPC API
gRPC is a remote procedure call framework commonly used for communication between services.
It frequently uses Protocol Buffers to define messages and service contracts.
Example contract:
syntax = "proto3";
service CustomerService {
rpc GetCustomer(CustomerRequest)
returns (CustomerResponse);
}
message CustomerRequest {
string customer_id = 1;
}
message CustomerResponse {
string name = 1;
string email = 2;
}
gRPC supports efficient binary serialization and streaming.
It is often useful for internal services where strong contracts and performance are important.
REST vs SOAP vs GraphQL vs gRPC
| Feature | REST | SOAP | GraphQL | gRPC |
|---|---|---|---|---|
| Approach | Architectural style | Messaging protocol | Query language and runtime | RPC framework |
| Typical format | JSON | XML | JSON | Protocol Buffers |
| Client data selection | Endpoint-defined | Operation-defined | Flexible field selection | Contract-defined |
| Streaming | Requires suitable mechanisms | Limited by implementation | Subscription support | Built-in streaming |
| Common use | Public and internal APIs | Enterprise integrations | Data-rich applications | Service-to-service communication |
Which should you learn first?
Start with HTTP and REST-style APIs. They provide a practical foundation for understanding the other technologies.
PART 3: BUILD YOUR FIRST API
12. Create a REST API Using Node.js and Express
Now let's build a real API.
We will create a simple Book Management API.
Our API will allow users to:
- View all books
- View a specific book
- Add a new book
- Update an existing book
- Delete a book
- Search books
- Use pagination
We will use Node.js and Express because they are relatively easy to understand.
Prerequisites
You need:
- Node.js 20 or a newer supported version
- A code editor such as Visual Studio Code
- A terminal
- Basic JavaScript knowledge
Step 1: Create the project
Open a terminal and run:
mkdir book-api
cd book-api
npm init -y
This creates a Node.js project with a package.json file.
Step 2: Install Express
npm install express
Express is a framework for building HTTP servers and APIs in Node.js.
Step 3: Create server.js
Create a file named server.js.
Add the following code:
const express = require("express");
const { randomUUID } = require("node:crypto");
const app = express();
const PORT = process.env.PORT || 3000;
app.use(express.json({ limit: "100kb" }));
let books = [
{
id: "1",
title: "Learn JavaScript",
author: "John Smith",
price: 499
},
{
id: "2",
title: "Learn Node.js",
author: "David Miller",
price: 599
}
];
function validateBook(data) {
if (
!data ||
typeof data !== "object" ||
Array.isArray(data)
) {
return "A valid JSON object is required.";
}
if (
typeof data.title !== "string" ||
!data.title.trim()
) {
return "A non-empty title is required.";
}
if (
typeof data.author !== "string" ||
!data.author.trim()
) {
return "A non-empty author is required.";
}
if (
typeof data.price !== "number" ||
!Number.isFinite(data.price) ||
data.price < 0
) {
return "Price must be a non-negative number.";
}
return null;
}
// GET all books with search and pagination
app.get("/api/books", (req, res) => {
const page = Number(req.query.page ?? 1);
const limit = Number(req.query.limit ?? 10);
if (
!Number.isInteger(page) ||
!Number.isInteger(limit) ||
page < 1 ||
limit < 1 ||
limit > 100
) {
return res.status(400).json({
error: "Invalid pagination parameters."
});
}
const search = String(req.query.search ?? "")
.trim()
.toLowerCase();
const filtered = books.filter(book =>
book.title.toLowerCase().includes(search)
);
const start = (page - 1) * limit;
res.json({
page,
limit,
total: filtered.length,
data: filtered.slice(start, start + limit)
});
});
// GET a book by ID
app.get("/api/books/:id", (req, res) => {
const book = books.find(
item => item.id === req.params.id
);
if (!book) {
return res.status(404).json({
error: "Book not found."
});
}
res.json(book);
});
// POST create a book
app.post("/api/books", (req, res) => {
const error = validateBook(req.body);
if (error) {
return res.status(400).json({ error });
}
const book = {
id: randomUUID(),
title: req.body.title.trim(),
author: req.body.author.trim(),
price: req.body.price
};
books.push(book);
res
.status(201)
.location(`/api/books/${book.id}`)
.json(book);
});
// PATCH update a book
app.patch("/api/books/:id", (req, res) => {
const book = books.find(
item => item.id === req.params.id
);
if (!book) {
return res.status(404).json({
error: "Book not found."
});
}
const allowed = ["title", "author", "price"];
if (
!req.body ||
typeof req.body !== "object" ||
Array.isArray(req.body) ||
Object.keys(req.body).length === 0 ||
Object.keys(req.body).some(
key => !allowed.includes(key)
)
) {
return res.status(400).json({
error: "Provide valid fields to update."
});
}
const updated = {
...book,
...req.body
};
const error = validateBook(updated);
if (error) {
return res.status(400).json({ error });
}
updated.title = updated.title.trim();
updated.author = updated.author.trim();
Object.assign(book, updated);
res.json(book);
});
// DELETE a book
app.delete("/api/books/:id", (req, res) => {
const index = books.findIndex(
item => item.id === req.params.id
);
if (index === -1) {
return res.status(404).json({
error: "Book not found."
});
}
books.splice(index, 1);
res.status(204).send();
});
// Handle unexpected errors
app.use((err, req, res, next) => {
if (
err instanceof SyntaxError &&
err.status === 400 &&
"body" in err
) {
return res.status(400).json({
error: "Invalid JSON request body."
});
}
console.error(err);
res.status(500).json({
error: "Internal server error."
});
});
app.listen(PORT, () => {
console.log(
`Book API running at http://localhost:${PORT}`
);
});
Step 4: Start the server
Run:
node server.js
You should see:
Book API running at http://localhost:3000
Congratulations! Your API server is now running.
Step 5: Test the GET endpoint
Open your browser and visit:
http://localhost:3000/api/books
Expected response:
{
"page": 1,
"limit": 10,
"total": 2,
"data": [
{
"id": "1",
"title": "Learn JavaScript",
"author": "John Smith",
"price": 499
},
{
"id": "2",
"title": "Learn Node.js",
"author": "David Miller",
"price": 599
}
]
}
You have successfully created your first REST-style API.
Important note
This is a learning project.
The books are stored in memory, meaning changes disappear when the server restarts.
The API also does not implement authentication, persistent storage, or production security controls.
Do not expose this demonstration publicly as a production service without adding those safeguards.
PART 4: HOW TO USE AN API
13. Call an API Using cURL
cURL is a command-line tool for transferring data using protocols such as HTTP.
It is widely used by developers for debugging and testing APIs.
GET request
curl http://localhost:3000/api/books
GET a particular book
curl http://localhost:3000/api/books/1
POST request
curl -X POST http://localhost:3000/api/books \
-H "Content-Type: application/json" \
-d '{
"title": "Mastering APIs",
"author": "Alex Johnson",
"price": 799
}'
The backslash line continuation shown above is suitable for Unix-like shells. Windows PowerShell has different quoting and line-continuation rules; curl.exe can also be used explicitly to invoke the executable.
PATCH request
Replace BOOK_ID with the ID returned by the POST request.
Replace BOOK_ID with the id returned by your POST /api/books request.
curl -X PATCH \
http://localhost:3000/api/books/BOOK_ID \
-H "Content-Type: application/json" \
-d '{"price": 699}'
DELETE request
curl -X DELETE \
http://localhost:3000/api/books/BOOK_ID
When successful, the DELETE operation returns HTTP 204 without a response body.
Useful cURL options
| Option | Meaning |
|---|---|
-X | HTTP method |
-H | Request header |
-d | Request body |
-i | Include response headers |
-v | Verbose diagnostic output |
-L | Follow redirects |
--max-time | Set a total operation time limit |
14. Call an API Using JavaScript Fetch
JavaScript provides the Fetch API for making HTTP requests.
GET example
async function getBooks() {
const response = await fetch(
"http://localhost:3000/api/books"
);
if (!response.ok) {
throw new Error(
`HTTP error: ${response.status}`
);
}
const result = await response.json();
console.log(result);
}
getBooks().catch(console.error);
POST example
async function createBook() {
const response = await fetch(
"http://localhost:3000/api/books",
{
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
title: "API Development Guide",
author: "Jane Wilson",
price: 999
})
}
);
const result = await response.json();
if (!response.ok) {
throw new Error(
result.error || "Request failed"
);
}
console.log("Created:", result);
}
createBook().catch(console.error);
Important Fetch behavior
Fetch does not automatically reject its promise when the server returns HTTP 400 or 500.
You must inspect response.ok or response.status to detect unsuccessful HTTP responses.
Network failures are different and usually reject the promise.
Also, browsers enforce cross-origin rules. If your frontend runs on a different origin from your API, the API may need an appropriate CORS configuration.
15. Test an API Using Postman
Postman is a popular tool for sending requests to APIs.
To test the Book API:
- Open Postman.
- Create a new HTTP request.
- Choose the GET method.
- Enter
http://localhost:3000/api/books. - Click Send.
- Inspect the response body and status code.
To create a book, select POST, choose a raw JSON request body, and enter:
{
"title": "Learning REST APIs",
"author": "Michael Brown",
"price": 450
}
Send the request.
You should receive a response with HTTP status 201 Created.
What is a Postman collection?
A Postman collection is a group of saved requests.
It allows teams to organize APIs by folders, environments, and features.
For example:
Book Management Collection
|
|-- Books
| |-- GET All Books
| |-- GET Book By ID
| |-- POST Create Book
| |-- PATCH Update Book
| |-- DELETE Book
|
|-- Authentication
|-- Login
|-- Refresh Token
Collections can be exported, imported, shared, and used in automated workflows.
16. Create and Test Mock APIs
Sometimes a frontend developer needs an API before the backend is finished.
A mock API solves this problem.
A mock API returns predefined responses without needing the complete real backend implementation.
For example, suppose a shopping application expects:
GET /api/orders/101
A mock response might be:
{
"orderId": 101,
"customer": "Rahul",
"status": "Shipped",
"total": 2499
}
The frontend team can build and test the order tracking page without waiting for a real database or order processing system.
Benefits of mock APIs
- Faster frontend development
- Independent team development
- Predictable test responses
- Testing error scenarios
- Prototyping
- API contract validation
Try the ProgToolKit API Playground
You can explore API creation, mocking, and request testing using the developer utilities available at ProgToolKit.
Mock APIs are especially useful when the production service is unavailable, incomplete, or costly to call repeatedly.
PART 5: API AUTHENTICATION AND SECURITY
17. What Is API Authentication?
Authentication verifies who or what is making a request.
Authorization determines which actions that caller is allowed to perform.
For example:
A customer might be authenticated successfully but still not have permission to view another customer's private orders.
Common API authentication approaches include:
- API keys
- HTTP Basic authentication
- Bearer tokens
- OAuth 2.0
- OpenID Connect
- Mutual TLS for service identities
API key example
GET /api/orders
X-API-Key: YOUR_API_KEY
The backend validates the key before processing the operation.
API keys can identify callers or applications, but a key alone does not necessarily identify the end user.
Bearer token example
GET /api/orders
Authorization: Bearer YOUR_ACCESS_TOKEN
The server validates the access token and checks the requested permissions.
Never store production secrets directly in publicly accessible frontend source code.
18. What Is JWT?
JWT stands for JSON Web Token.
A JWT is a compact token format that can carry claims about a subject and other information.
A typical signed JWT contains three encoded sections:
HEADER.PAYLOAD.SIGNATURE
Header
Example:
{
"alg": "RS256",
"typ": "JWT"
}
Payload
Example:
{
"sub": "user-101",
"role": "customer",
"exp": 1893456000
}
Signature
The signature helps the receiver verify that the signed content has not been altered.
A JWT's header and payload are usually encoded, not encrypted.
Never put passwords or confidential information in a normal signed JWT payload.
JWT validation checklist
A backend receiving JWT access tokens should validate:
- Signature
- Trusted signing algorithm and key
- Token expiration
- Expected issuer
- Expected audience
- Relevant permissions or scopes
A JWT that can be decoded is not necessarily valid or trustworthy.
19. OAuth 2.0 Explained
OAuth 2.0 is an authorization framework.
It allows applications to obtain limited access to resources, often without sharing the user's password with the requesting application.
For example, an application may request permission to access selected information from a third-party service.
A simplified authorization flow:
User
|
v
Application
|
| Request Authorization
v
Authorization Server
|
| User Grants Permission
v
Authorization Code
|
| Secure Token Exchange
v
Access Token
|
| Authorized API Request
v
Resource Server
Modern applications commonly use Authorization Code Flow with PKCE for user-facing authorization flows.
For server-to-server integrations, Client Credentials Flow may be appropriate.
OAuth vs OpenID Connect
OAuth 2.0 primarily concerns authorization.
OpenID Connect, built on OAuth 2.0, adds a standard identity layer for authentication.
A service should not treat an arbitrary OAuth access token as proof that a user has logged into the application.
20. Common API Security Risks
Production APIs should defend against common security problems.
| Risk | Explanation | Protection |
|---|---|---|
| Broken object-level authorization | User accesses another user's data | Check permission for every requested object |
| Broken authentication | Weak identity verification | Secure token handling and authentication |
| Excessive resource usage | Requests consume too much processing power | Rate limits, quotas, size limits, timeouts |
| Injection | Untrusted data changes queries or commands | Parameterized queries and input validation |
| Sensitive data exposure | Confidential information is returned or logged | Data minimization and safe logging |
| Security misconfiguration | Unsafe default settings | Secure configuration reviews |
| Unsafe third-party API usage | External data is trusted without validation | Validate upstream responses |
| Mass assignment | Unwanted fields are updated | Explicitly allow updateable fields |
Minimum production security checklist
- Use HTTPS.
- Authenticate requests where necessary.
- Authorize access to individual resources.
- Validate incoming data.
- Protect sensitive credentials.
- Use parameterized database queries.
- Apply rate limiting and appropriate quotas.
- Avoid exposing detailed internal errors.
- Implement secure logging and monitoring.
- Keep dependencies updated.
- Configure CORS deliberately.
- Apply request size limits and timeouts.
- Audit API permissions regularly.
For a deeper security reference, review the OWASP API Security Top 10.
PART 6: DESIGNING PROFESSIONAL APIs
21. API Design Best Practices
A good API should be consistent, predictable, secure, and easy to understand.
Use resource-oriented URLs
Preferred:
GET /api/customers
GET /api/customers/101
POST /api/customers
Less consistent:
GET /api/getAllCustomers
POST /api/createNewCustomer
Resource-oriented paths make APIs easier to discover and maintain.
Use appropriate HTTP methods
Use GET to retrieve information and POST to create resources or submit operations.
Do not use GET to perform destructive actions.
Use consistent JSON responses
Example success response:
{
"data": {
"id": 101,
"name": "Rahul"
}
}
Example error:
{
"error": {
"code": "VALIDATION_ERROR",
"message": "Customer name is required."
}
}
A predictable format makes frontend integration easier.
Do not expose unnecessary information
If the client needs a customer's name and city, avoid returning password hashes, internal security settings, or unrelated private information.
Use consistent naming
Choose a convention and apply it consistently.
For example:
{
"customerId": 101,
"firstName": "Rahul",
"lastName": "Sharma"
}
Avoid mixing customerId, first_name, and CustomerID without a clear contract.
22. API Versioning
APIs change over time.
Suppose your original API returns:
{
"customerName": "Rahul"
}
A future version might return:
{
"firstName": "Rahul",
"lastName": "Sharma"
}
Changing an existing property can break applications that depend on the old response.
API versioning helps manage such changes.
A common URL-based approach is:
/api/v1/customers
/api/v2/customers
Other approaches include header-based and media-type versioning.
Versioning best practices
- Avoid unnecessary breaking changes.
- Prefer additive changes when possible.
- Communicate deprecations.
- Maintain a compatibility policy.
- Provide migration documentation.
- Use contract tests to identify unexpected changes.
Not every small API change requires a new major version.
23. API Pagination
Imagine an e-commerce API containing one million products.
Returning every product in a single request would be inefficient.
Pagination solves this problem.
Page-based pagination
Request:
GET /api/products?page=2&limit=25
Response:
{
"page": 2,
"limit": 25,
"total": 250,
"totalPages": 10,
"data": [
{
"id": 26,
"name": "Product 26"
}
]
}
The data array above is shortened for illustration.
Cursor-based pagination
Cursor-based pagination uses a position marker instead of a page number.
Example:
GET /api/products?limit=25&cursor=abc123
Cursor pagination can provide more stable results for changing datasets when combined with a deterministic sort order.
It is commonly useful for large collections, activity feeds, and APIs where records are frequently added or removed.
24. API Filtering and Sorting
API consumers often need more control over returned information.
Example:
GET /api/products?category=electronics&sort=price&order=asc
Here:
categoryfilters the results.sortselects the sorting field.orderdetermines ascending or descending order.
Recommended practices
Validate allowed filter and sort fields.
Set limits on page size.
Avoid allowing clients to inject raw SQL expressions through sorting or filtering parameters.
25. API Rate Limiting
Rate limiting restricts how frequently a client can access an API.
For example:
Maximum: 100 requests per minute
If a client exceeds the limit, the server may return:
HTTP/1.1 429 Too Many Requests
Retry-After: 60
The retry value is illustrative.
Why rate limiting matters
Rate limiting helps:
- Protect infrastructure
- Reduce resource exhaustion
- Prevent abusive traffic
- Enforce service quotas
- Control costs
- Improve fairness between clients
Common rate limiting algorithms include:
- Fixed window
- Sliding window
- Token bucket
- Leaky bucket
For distributed applications, rate-limit counters may need a shared store rather than process-local memory.
26. API Caching
Caching stores reusable results so that repeated requests do not always require complete backend processing.
Example:
Client
|
v
API Gateway
|
v
Cache
|
| Cache Miss
v
Database
If the result is already cached and valid, the API can return it more quickly.
HTTP caching headers
Example:
Cache-Control: public, max-age=60
ETag: "product-list-v2"
max-age=60 indicates a freshness lifetime of 60 seconds under the relevant caching rules.
An ETag is a validator that allows clients and caches to check whether a representation has changed.
A conditional request may include:
If-None-Match: "product-list-v2"
If the representation has not changed, the server may return:
304 Not Modified
Important caching rule
Avoid placing personalized or confidential data into publicly shared caches.
Choose the cache policy according to the sensitivity and freshness requirements of the resource.
PART 7: API TESTING AND DEBUGGING
27. Different Types of API Testing
Professional teams test APIs at multiple levels.
Functional testing
Verify whether the API produces the expected result.
Example:
Given: Valid book details
When: POST /api/books
Then: HTTP 201 is returned
Validation testing
Check invalid inputs.
Examples:
- Missing required field
- Invalid JSON
- Negative product price
- Invalid pagination value
Authentication testing
Verify that unauthenticated requests are rejected where authentication is required.
Authorization testing
Verify that users cannot access resources belonging to other users without permission.
Integration testing
Verify communication with real databases, message queues, and downstream services.
Performance testing
Measure response time, throughput, resource usage, and behavior under different levels of load.
Contract testing
Confirm that API request and response structures continue to match the published contract.
Security testing
Check for vulnerabilities such as broken authorization, injection, exposed sensitive information, and misconfiguration.
28. Example API Test Cases
| Test case | Expected result |
|---|---|
| GET existing book | 200 |
| GET nonexistent book | 404 |
| POST valid book | 201 |
| POST without title | 400 |
| POST with negative price | 400 |
| PATCH existing book | 200 |
| PATCH invalid field | 400 |
| DELETE existing book | 204 |
| DELETE nonexistent book | 404 |
| Invalid JSON body | 400 |
For production APIs, expand these scenarios to include authentication, authorization, concurrency, rate limits, error recovery, and downstream failures.
29. Common API Errors and How to Fix Them
400 Bad Request
Possible causes:
- Invalid JSON
- Missing required parameters
- Incorrect field types
- Unsupported request structure
How to troubleshoot:
Inspect request headers, body, query parameters, and API documentation.
401 Unauthorized
Possible causes:
- Missing token
- Expired token
- Invalid signature
- Incorrect authentication scheme
How to troubleshoot:
Check the token, authorization header, issuer, audience, and expiry.
403 Forbidden
The caller may be authenticated but lack permission.
Check authorization policies and resource ownership.
404 Not Found
Possible causes:
- Incorrect path
- Wrong resource ID
- Wrong API version
- Resource not available
409 Conflict
A requested operation conflicts with the current resource state.
Examples include a duplicate unique identifier or an invalid state transition.
500 Internal Server Error
Possible causes:
- Unhandled application exception
- Unexpected database failure
- Incorrect server configuration
Check server logs and use a request identifier to trace the failure.
Do not expose internal stack traces to public clients.
503 Service Unavailable
The service may be temporarily unable to process the request.
Possible causes include maintenance, overload, or unavailable dependencies.
Clients should retry only when appropriate, preferably with bounded exponential backoff and jitter.
PART 8: ADVANCED API CONCEPTS
30. API Gateway
An API gateway is a component that sits between API consumers and backend services.
For example:
Mobile App Web App Partner App
| | |
+-------------+-------------+
|
v
API Gateway
|
+-------+-------+
| | |
v v v
User Order Payment
API API API
An API gateway may provide:
- Request routing
- Authentication integration
- Rate limiting
- API version routing
- Monitoring
- Request transformation
- Policy enforcement
An API gateway does not replace application-level authorization.
Even if the gateway authenticates a request, backend services should still enforce relevant resource permissions.
31. Microservices and APIs
Microservices architecture divides an application into smaller services organized around business capabilities.
For example, an online shopping platform may contain:
Customer Service
Product Service
Inventory Service
Order Service
Payment Service
Notification Service
Each service may expose an API or communicate through messaging infrastructure.
Advantages
- Independent deployment
- Independent scaling
- Smaller service boundaries
- Technology flexibility
- Team ownership
Challenges
- Network failures
- Distributed transactions
- Data consistency
- Debugging across services
- Version management
- Operational complexity
Microservices are not always the best solution.
For smaller applications, a well-structured monolith is often simpler to build, test, and maintain.
32. Synchronous vs Asynchronous APIs
Synchronous communication
The caller sends a request and waits for a response.
Example:
Client -> Order API -> Database
Client <- Order API <- Database
This is suitable when the result can be returned within an acceptable response time.
Asynchronous communication
The request starts an operation that finishes later.
Example:
Client
|
v
Order API
|
v
Message Queue
|
v
Order Processor
|
v
Database
The API may immediately return:
HTTP/1.1 202 Accepted
Location: /api/jobs/abc123
{
"jobId": "abc123",
"status": "Pending"
}
The client can check the operation later or receive a callback.
Asynchronous processing is useful for:
- Report generation
- Large file processing
- Video conversion
- Email workflows
- Order fulfillment
- Batch integrations
33. Webhooks
A webhook allows one application to notify another application when an event occurs.
Instead of repeatedly asking whether something changed, the receiving application is notified.
Example: Payment processing.
Customer Makes Payment
|
v
Payment Provider
|
| Webhook POST
v
Merchant Application
|
v
Update Order Status
Example webhook payload:
{
"event": "payment.succeeded",
"eventId": "evt_12345",
"data": {
"paymentId": "pay_98765",
"amount": 1500,
"currency": "INR"
}
}
Webhook security best practices
- Validate the provider's cryptographic signature.
- Use HTTPS.
- Reject invalid events.
- Handle duplicate deliveries.
- Store processed event identifiers.
- Return success only according to the provider's delivery contract.
- Use retry-safe event processing.
Many webhook providers use at-least-once delivery, so duplicate events should be expected.
34. API Idempotency and Duplicate Prevention
Consider an API that creates a payment.
A client sends a request, but the network connection fails before it receives the response.
The client does not know whether the payment succeeded.
If it sends the request again, there is a risk of creating a second payment.
One solution is an idempotency key.
Example:
POST /api/payments
Idempotency-Key: payment-order-5001
Content-Type: application/json
{
"orderId": "5001",
"amount": 1500,
"currency": "INR"
}
The backend stores the key and the associated operation result according to its retention and conflict rules.
If the same operation is retried using the same key, the API can return the previously established result rather than executing the payment twice.
A robust implementation must also handle concurrent requests using the same key.
Idempotency is particularly important for financial transactions, order creation, and message processing.
35. Eventual Consistency
In distributed systems, data changes may not become visible in every service immediately.
For example:
- A customer creates an order.
- Order Service saves the order.
- An event is published.
- Inventory Service processes the event.
- A reporting system updates later.
During this process, different services may temporarily show different information.
This is called eventual consistency.
How to design for eventual consistency
- Define acceptable consistency delays.
- Provide clear processing statuses.
- Use reliable event delivery.
- Handle duplicate events.
- Build reconciliation processes.
- Monitor delayed or failed messages.
- Avoid promising immediate consistency when it is not guaranteed.
36. API Observability
A production API should be observable.
Observability helps developers understand what is happening inside a system.
Three common signals are:
Logs
Records of significant events.
Example:
RequestId=req-101
Method=POST
Path=/api/orders
Status=201
DurationMs=125
Metrics
Numerical measurements collected over time.
Examples:
- Requests per second
- Error rate
- Response time
- CPU usage
- Memory usage
- Queue depth
Distributed traces
Traces help track a request across multiple services.
Example:
API Gateway 10 ms
|
Order Service 35 ms
|
Inventory Service 45 ms
|
Database 20 ms
Distributed tracing is especially important in microservices architectures.
Important API performance metrics
| Metric | Meaning |
|---|---|
| Throughput | Number of requests processed per second |
| Error rate | Percentage of requests resulting in errors |
| p50 latency | Median response time |
| p95 latency | Time within which 95% of measured requests complete |
| p99 latency | Time within which 99% of measured requests complete |
| Availability | Proportion of time or requests meeting the availability definition |
| Saturation | How close resources are to their operational limits |
Rather than monitoring only average response time, professional teams often pay attention to p95 and p99 latency.
37. API Resilience: Timeouts, Retries, and Circuit Breakers
APIs depend on networks and other services, which can fail.
A resilient client should expect those failures.
Timeouts
Set appropriate limits so requests do not wait indefinitely.
Retries
Retry selected transient failures, such as temporary network issues or certain server errors.
Avoid retrying operations blindly if doing so could duplicate a transaction.
Exponential backoff
Increase the delay between retry attempts.
Example:
Attempt 1 -> immediate
Attempt 2 -> after 1 second
Attempt 3 -> after 2 seconds
Attempt 4 -> after 4 seconds
These are illustrative delays. Production retry policies should include limits and randomized jitter.
Circuit breaker
A circuit breaker temporarily stops calls to a failing dependency to reduce cascading failures.
Bulkhead isolation
Bulkheads separate resource pools so failures in one dependency do not exhaust all application capacity.
Expert principle
Reliability requires more than retries.
You also need bounded concurrency, timeouts, duplicate protection, monitoring, and sensible failure handling.
PART 9: API DOCUMENTATION AND DEPLOYMENT
38. Document APIs Using OpenAPI and Swagger
Good API documentation helps developers understand how to integrate with your service.
An API specification should describe:
- Endpoints
- HTTP methods
- Request parameters
- Request bodies
- Responses
- Status codes
- Authentication
- Error behavior
- Examples
OpenAPI is a widely used specification for describing HTTP APIs.
Swagger is a collection of tools associated with API design, documentation, and testing.
Simple OpenAPI example
openapi: 3.0.3
info:
title: Book API
version: 1.0.0
description: API for managing books
servers:
- url: http://localhost:3000
paths:
/api/books:
get:
summary: Retrieve books
responses:
'200':
description: Books retrieved successfully
content:
application/json:
schema:
type: object
properties:
page:
type: integer
limit:
type: integer
total:
type: integer
data:
type: array
items:
type: object
properties:
id:
type: string
title:
type: string
author:
type: string
price:
type: number
Try it: paste this book API specification into OpenAPI Studio, select Validate & preview, and open Swagger Viewer.
This is a simplified specification covering the GET operation only.
In a real project, document the remaining operations, validation rules, schemas, and security requirements.
39. How to Deploy an API
So far, our API runs locally:
http://localhost:3000
Other internet users cannot directly access this local server.
To make the API publicly available, you need suitable hosting infrastructure.
Possible hosting options include:
- Cloud application hosting
- Containers
- Virtual machines
- Managed application platforms
- Serverless functions
Typical deployment process
Developer Writes Code
|
v
Source Control Repository
|
v
Automated Build
|
v
Automated Tests
|
v
Security Checks
|
v
Deployment
|
v
Production API
|
v
Monitoring and Alerts
Before deploying to production
Replace temporary in-memory storage with a persistent database.
Add authentication and authorization.
Configure environment variables and secret management.
Use HTTPS.
Add health checks.
Configure request limits and timeouts.
Set up monitoring and alerts.
Use automated tests and deployment pipelines.
Establish a backup and recovery strategy.
PART 10: ADVANCED API DEVELOPMENT CHECKLIST
40. What Makes an API Production-Ready?
Before releasing an API to real users, review the following checklist.
API design
- [ ] Consistent endpoint naming
- [ ] Correct HTTP methods
- [ ] Meaningful status codes
- [ ] Request validation
- [ ] Consistent error responses
- [ ] Pagination for large collections
- [ ] Clear API documentation
- [ ] Compatibility and versioning strategy
Security
- [ ] HTTPS enabled
- [ ] Authentication configured
- [ ] Resource-level authorization
- [ ] Secrets securely stored
- [ ] Sensitive information excluded from logs
- [ ] Input validation
- [ ] Injection protection
- [ ] Rate limiting
- [ ] CORS appropriately configured
Reliability
- [ ] Request timeouts
- [ ] Safe retry policies
- [ ] Duplicate prevention where required
- [ ] Database failure handling
- [ ] Health checks
- [ ] Graceful shutdown
- [ ] Backup and recovery procedures
Monitoring
- [ ] Structured logging
- [ ] Request IDs
- [ ] Error monitoring
- [ ] Latency metrics
- [ ] Distributed tracing where useful
- [ ] Alerts for critical failures
Testing
- [ ] Unit tests
- [ ] Integration tests
- [ ] API contract tests
- [ ] Security tests
- [ ] Performance tests
- [ ] Deployment smoke tests
Not every project needs every advanced architectural component, but every production API should have security and reliability practices appropriate to its risks.
PART 11: FREQUENTLY ASKED QUESTIONS
41. What is an API in simple words?
An API is a defined way for software applications to communicate and exchange information.
For example, a shopping application may use a payment API to process transactions without building its own payment network.
42. What is the difference between an API and a REST API?
API is a broad term for software interfaces.
A REST API is a type of API designed according to REST architectural constraints.
All REST APIs are APIs, but not all APIs are REST APIs.
43. Is an API the same as a backend?
No.
A backend is the server-side part of an application that may contain business logic, database access, background processing, and integrations.
An API is an interface through which other software can interact with functionality.
A backend may expose multiple APIs.
44. Can I create an API for free?
Yes.
You can create and run an API locally using free tools such as Node.js, Python, Java, or .NET.
Public hosting may have costs depending on the provider, traffic, and infrastructure requirements.
45. Which programming language is best for API development?
There is no single best language.
Popular choices include:
- JavaScript and TypeScript with Node.js
- Python with FastAPI or Django
- C# with ASP.NET Core
- Java with Spring Boot
- Go with its standard HTTP libraries or frameworks
Choose based on your requirements, existing systems, team expertise, and deployment environment.
46. What is the difference between API and SDK?
An API defines an interface or contract.
An SDK, or Software Development Kit, is a collection of development tools, libraries, and documentation that helps developers build applications or integrate with a platform.
An SDK may include a client library that calls an API.
47. What is the difference between an API key and an access token?
An API key is commonly used to identify an application or API consumer.
An access token represents granted access under a particular authorization scheme and may have scopes, expiration, and other restrictions.
The exact security characteristics depend on the provider and implementation.
48. How do I know whether my API works?
Send a request and verify:
- Status code
- Response body
- Response headers
- Expected business behavior
- Validation behavior
- Authorization rules
- Database changes where relevant
You can use cURL, Postman, automated tests, or an API testing tool.
49. How can I make an API faster?
Common approaches include:
- Optimize database queries.
- Use pagination.
- Cache suitable responses.
- Reduce unnecessary downstream calls.
- Compress large responses when appropriate.
- Avoid returning unnecessary fields.
- Reuse network connections.
- Measure bottlenecks before optimizing.
The right solution depends on what is actually causing latency.
50. How long does it take to learn API development?
You can understand basic API concepts and create a small working API relatively quickly.
Building reliable production APIs requires more experience with security, databases, testing, networking, deployment, and distributed systems.
The most effective approach is to build progressively more complex projects.
PART 12: A PRACTICAL API LEARNING ROADMAP
Beginner Level
Goal: Understand APIs and make basic requests.
Learn:
- What an API is.
- HTTP requests and responses.
- GET, POST, PUT, PATCH, DELETE.
- JSON.
- Status codes.
- Headers and parameters.
- cURL and API testing tools.
Practice project: Build a Book Management API.
Intermediate Level
Goal: Build database-backed, authenticated APIs.
Learn:
- SQL and database integration.
- Authentication and authorization.
- Input validation.
- Error handling.
- Pagination and filtering.
- API documentation.
- Unit and integration testing.
- Deployment.
Practice project: Build an e-commerce product and order API.
Advanced Level
Goal: Build secure and maintainable production APIs.
Learn:
- OAuth 2.0 and OpenID Connect.
- API gateways.
- Distributed tracing.
- Rate limiting.
- Caching.
- API versioning.
- Contract testing.
- CI/CD pipelines.
- Security threat modeling.
- API performance optimization.
Practice project: Build an authenticated order management system with database persistence, caching, and monitoring.
Expert Level
Goal: Design resilient, scalable API ecosystems.
Learn:
- Distributed systems.
- Event-driven architecture.
- Reliable messaging.
- Idempotency.
- Eventual consistency.
- Circuit breakers.
- Observability.
- Service-level objectives.
- Distributed transactions and sagas.
- High-availability architecture.
- Zero-trust security principles.
- API governance and lifecycle management.
Practice project: Design a multi-service order processing platform with payment integration, event-driven processing, automated recovery, and end-to-end observability.
Final Thoughts
APIs are one of the foundations of modern software development.
They allow applications to communicate, share data, automate workflows, and integrate with services built by other teams and organizations.
The most important concepts to remember are:
- An API defines how software systems communicate.
- HTTP APIs use methods, URLs, headers, and optional request bodies.
- REST is an architectural style, not the only type of API.
- Authentication and authorization are different responsibilities.
- Secure APIs validate inputs and enforce permissions.
- Reliable APIs handle failures, retries, and duplicate requests carefully.
- Professional API development includes documentation, testing, monitoring, and maintenance.
You do not need to understand every advanced concept before creating your first API.
Start with a simple GET request, create a POST endpoint, connect a database, add authentication, and gradually build more sophisticated functionality.
The best way to learn APIs is to build them, test them, and understand how they behave when things go wrong.
Start practicing
Explore developer utilities at ProgToolKit.com to work with JSON, data conversion, API requests, and mock APIs.
Build your first API today. Then improve it one concept at a time.
Further Reading and Official References
- MDN: HTTP Overview
- MDN: HTTP Request Methods
- Express.js Documentation
- OpenAPI Specification
- OWASP API Security Top 10
- OAuth 2.0 Framework — RFC 6749
- HTTP Semantics — RFC 9110
This article is intended for educational purposes. Demonstration code must be adapted and security-reviewed before production deployment.