Guides › API Development & Testing
REST API Development: Complete Beginner to Advanced Guide
Learn REST API development, HTTP methods, status codes, routing, validation, authentication, error handling, pagination, and API security.
REST API Development: Complete Beginner to Advanced Guide
1. Introduction to APIs
An API (Application Programming Interface) allows software systems to communicate through defined rules and interfaces.
For example, a weather application can request weather information from a server through an API instead of storing all weather data itself.
What You Will Learn
- API fundamentals and REST architecture
- HTTP methods, headers, and status codes
- JSON request and response formats
- RESTful resource and URL design
- Building APIs with Node.js and Express
- Input validation and error handling
- Authentication and authorization
- Database integration
- Pagination, filtering, and sorting
- API documentation and versioning
- Security, testing, deployment, and monitoring
2. What Is a REST API?
REST stands for Representational State Transfer. It is an architectural style for designing networked applications.
REST APIs commonly use HTTP and represent resources through URLs.
Example resources:
/api/users/api/products/api/orders
A REST-style API uses HTTP methods to describe the operation being performed on a resource.
REST is an architectural style, not a specific programming language or framework.
3. How an API Request Works
A typical request-response flow is:
- A client sends an HTTP request.
- The server receives the request.
- The server validates the request.
- Authentication and authorization are checked when required.
- Application logic processes the operation.
- The server reads or updates data.
- The server returns an HTTP response.
Example:
GET /api/products/101 HTTP/1.1
Host: example.com
Accept: application/json
Possible response:
HTTP/1.1 200 OK
Content-Type: application/json
{
"id": 101,
"name": "Keyboard",
"price": 1499
}
4. HTTP Methods
GET
Retrieves a resource or collection.
GET /api/products
POST
Creates a resource or initiates an operation.
POST /api/products
Content-Type: application/json
{
"name": "Mouse",
"price": 599
}
PUT
Typically replaces a resource representation.
PATCH
Partially updates a resource.
DELETE
Requests removal of a resource.
HEAD and OPTIONS
HEADretrieves response headers without the response body.OPTIONSdescribes communication options supported by a resource, often including CORS-related behavior.
Safe and idempotent methods are important API design concepts. GET is intended to be safe; PUT and DELETE are generally idempotent. POST is not inherently idempotent.
5. HTTP Status Codes
Success
200 OK— request succeeded.201 Created— a resource was created.202 Accepted— request accepted for processing.204 No Content— request succeeded with no response body.
Client Errors
400 Bad Request— invalid request.401 Unauthorized— valid authentication credentials are missing or invalid.403 Forbidden— access is not permitted.404 Not Found— resource not found.409 Conflict— request conflicts with the current resource state.422 Unprocessable Content— request content cannot be processed according to the API's rules.429 Too Many Requests— rate limit exceeded.
Server Errors
500 Internal Server Error— unexpected server failure.502 Bad Gateway— invalid response from an upstream server.503 Service Unavailable— service temporarily unavailable.504 Gateway Timeout— upstream response timed out.
Choose status codes consistently and document the meaning of each response.
6. Design Resource URLs
Use nouns that represent resources.
Good examples:
GET /api/usersGET /api/users/42POST /api/usersPATCH /api/users/42DELETE /api/users/42
Avoid unnecessarily embedding actions in URLs when an HTTP method already describes the operation.
Use nested paths when they express a clear relationship, such as /api/users/42/orders.
Avoid deep nesting that makes resource access unnecessarily complicated.
7. Request and Response JSON
JSON is a common format for sending structured data.
Example request:
{
"name": "Aman",
"email": "aman@example.com"
}
Example response:
{
"id": 42,
"name": "Aman",
"email": "aman@example.com"
}
Use consistent naming, documented data types, predictable response shapes, and appropriate content types.
Never return passwords, password hashes, private tokens, or unnecessary internal database fields.
8. Build a REST API with Node.js and Express
Install Node.js, create a project, and install Express.
mkdir codify-api
cd codify-api
npm init -y
npm install express
Create server.js:
const express = require("express");
const app = express();
const PORT = process.env.PORT || 3000;
app.use(express.json());
let products = [
{ id: 1, name: "Keyboard", price: 1499 },
{ id: 2, name: "Mouse", price: 599 }
];
app.get("/api/products", (req, res) => {
res.json(products);
});
app.get("/api/products/:id", (req, res) => {
const id = Number(req.params.id);
const product = products.find(item => item.id === id);
if (!product) {
return res.status(404).json({
error: {
code: "PRODUCT_NOT_FOUND",
message: "Product not found"
}
});
}
res.json(product);
});
app.post("/api/products", (req, res) => {
const { name, price } = req.body;
if (
typeof name !== "string" ||
!name.trim() ||
typeof price !== "number" ||
!Number.isFinite(price) ||
price < 0
) {
return res.status(400).json({
error: {
code: "INVALID_PRODUCT",
message: "A name and a valid non-negative price are required"
}
});
}
const product = {
id: Math.max(0, ...products.map(item => item.id)) + 1,
name: name.trim(),
price
};
products.push(product);
res.status(201).json(product);
});
app.listen(PORT, () => {
console.log(`API running on port ${PORT}`);
});
Run the server:
node server.js
This example uses in-memory data for learning. Data disappears when the server restarts, so production applications should use a database and appropriate ID generation.
9. Add PUT, PATCH, and DELETE Routes
Example PATCH route:
app.patch("/api/products/:id", (req, res) => {
const id = Number(req.params.id);
const product = products.find(item => item.id === id);
if (!product) {
return res.status(404).json({
message: "Product not found"
});
}
const { name, price } = req.body;
if (name !== undefined) {
if (typeof name !== "string" || !name.trim()) {
return res.status(400).json({
message: "Name must be a non-empty string"
});
}
product.name = name.trim();
}
if (price !== undefined) {
if (
typeof price !== "number" ||
!Number.isFinite(price) ||
price < 0
) {
return res.status(400).json({
message: "Price must be a valid non-negative number"
});
}
product.price = price;
}
res.json(product);
});
Example DELETE route:
app.delete("/api/products/:id", (req, res) => {
const id = Number(req.params.id);
const index = products.findIndex(item => item.id === id);
if (index === -1) {
return res.status(404).json({
message: "Product not found"
});
}
products.splice(index, 1);
res.status(204).end();
});
For production systems, validate allowed fields, enforce ownership and permissions, and use persistent storage.
10. Input Validation
Never trust client input.
Validate:
- Required fields
- Data types
- String length
- Numeric ranges
- Email and identifier formats
- Allowed values
- Nested object structure
- Query parameters
- File upload limits
Use validation libraries such as Zod, Joi, or express-validator when appropriate.
Validation should be separate from business logic where practical. Reject unknown or disallowed fields when that is part of the API contract.
11. Centralized Error Handling
Use a consistent error response format.
{
"error": {
"code": "VALIDATION_ERROR",
"message": "The request contains invalid data",
"details": [
{
"field": "price",
"message": "Price must be non-negative"
}
]
}
}
In Express, centralized error middleware can handle unexpected failures.
app.use((err, req, res, next) => {
console.error(err);
if (res.headersSent) {
return next(err);
}
res.status(err.status || 500).json({
error: {
code: err.code || "INTERNAL_SERVER_ERROR",
message: err.status
? err.message
: "An unexpected error occurred"
}
});
});
Do not expose stack traces, database details, secrets, or internal infrastructure information to public clients.
12. Authentication and Authorization
Authentication answers: "Who are you?"
Authorization answers: "What are you allowed to do?"
Common authentication approaches include:
- Server-side sessions
- Access tokens
- OAuth 2.0 and OpenID Connect
- API keys for appropriate service-to-service use cases
Important practices:
- Hash passwords using a suitable password-hashing algorithm.
- Keep signing keys and secrets on the server.
- Use HTTPS.
- Validate token signature, issuer, audience, expiry, and relevant claims.
- Apply authorization checks to every protected resource.
- Rotate and revoke credentials where supported.
- Rate-limit login and sensitive endpoints.
An authenticated user should not automatically gain access to every user's records.
13. API Security
Follow a defense-in-depth approach.
- Enforce HTTPS.
- Validate and normalize input.
- Use parameterized database queries.
- Apply authentication and resource-level authorization.
- Set request body and upload size limits.
- Configure CORS deliberately.
- Use rate limiting and abuse detection.
- Protect against injection and broken access control.
- Avoid logging secrets or sensitive personal information.
- Keep dependencies patched.
- Use secure headers where appropriate.
- Store secrets in environment configuration or a secret manager.
- Apply least-privilege access to databases and services.
CORS is not an authentication mechanism. Hiding a route in frontend code is not authorization.
14. Pagination, Filtering, and Sorting
Avoid returning an unlimited number of records.
Example:
GET /api/products?page=2&limit=20&sort=price&order=asc
The server should:
- Validate the page and limit.
- Enforce a maximum page size.
- Allowlist sort fields and sort directions.
- Apply filtering and sorting safely.
- Return the requested page.
Example response:
{
"data": [
{
"id": 2,
"name": "Mouse",
"price": 599
}
],
"pagination": {
"page": 2,
"limit": 20,
"total": 101,
"totalPages": 6
}
}
Offset pagination is easy to implement. Cursor pagination can be more suitable for large or frequently changing datasets.
15. Database Integration
Common database choices include relational databases such as PostgreSQL and MySQL, and document databases such as MongoDB.
Use:
- Database constraints
- Parameterized queries or safe ORM methods
- Transactions for multi-step operations
- Indexes for frequent queries
- Connection pooling
- Migration tools
- Backups and restore testing
Do not assume that checking data in the API replaces database constraints. Enforce critical rules at the appropriate layers.
16. API Versioning
Versioning helps manage breaking changes.
Examples:
/api/v1/products
/api/v2/products
Other approaches include header-based versioning or media types.
Before introducing a new version, determine whether a backward-compatible change is possible. Document deprecated endpoints and give clients a reasonable migration path.
17. Idempotency and Retries
An operation is idempotent when repeating it has the same intended effect as performing it once.
PUT and DELETE are generally designed to be idempotent. POST operations may need an idempotency key when clients could retry a request after a timeout.
For payment or order creation:
- Generate a unique idempotency key on the client.
- Store the key and operation result safely on the server.
- Reject or safely handle conflicting reuse of a key.
- Avoid creating duplicate transactions on retries.
Use timeouts, bounded retries, and backoff for transient failures.
18. Rate Limiting
Rate limiting restricts how frequently clients can call an API.
Common strategies:
- Fixed window
- Sliding window
- Token bucket
- Leaky bucket
Rate limits may be applied per user, API key, IP address, or endpoint. For distributed deployments, use a shared rate-limit store when necessary.
Return 429 Too Many Requests when appropriate and document any retry guidance.
19. API Documentation with OpenAPI
OpenAPI provides a machine-readable description of HTTP APIs.
Document:
- Endpoints and methods
- Parameters
- Request bodies
- Response schemas
- Authentication
- Error responses
- Status codes
- Examples
- Versioning and deprecation
Tools such as Swagger UI can render interactive documentation from an OpenAPI specification.
Keep documentation synchronized with the implemented API and automated tests.
20. API Testing
Test multiple layers:
- Unit tests for business logic
- Integration tests for databases and services
- Contract tests for request and response shapes
- End-to-end tests for complete workflows
- Security tests for access control and invalid input
- Load tests for expected traffic patterns
Test success cases, invalid inputs, missing authentication, forbidden access, nonexistent records, rate limits, and server failures.
21. Deployment and Monitoring
Before deployment:
- Configure production environment variables.
- Set up HTTPS and network rules.
- Use a process manager or container platform.
- Apply database migrations safely.
- Configure health checks.
- Establish structured logging.
- Monitor latency, errors, traffic, and resource usage.
- Set alerts for important failures.
- Test backups and recovery.
- Document rollback procedures.
Do not log access tokens, passwords, or full sensitive request bodies.
22. Common API Design Mistakes
- Using incorrect HTTP status codes.
- Returning inconsistent response shapes.
- Skipping server-side validation.
- Exposing private database fields.
- Ignoring authorization checks.
- Returning every database record in one response.
- Exposing stack traces in production.
- Retrying unsafe operations without safeguards.
- Publishing undocumented breaking changes.
- Forgetting rate limits and request size limits.
- Failing to test error conditions.
- Assuming TypeScript types validate network data.
23. Practical Projects
Beginner
- Notes REST API
- Student management API
- Product catalog API
Intermediate
- User registration and login API
- Blog API with comments
- Expense tracker API
- Searchable inventory API
Advanced
- E-commerce order API
- Role-based task management API
- Booking API with concurrency safeguards
- API with pagination, caching, and rate limiting
Every project should include documentation, tests, validation, error handling, and deployment instructions.
24. Learning Roadmap
Week 1
Learn HTTP, JSON, resource URLs, methods, and status codes.
Week 2
Build CRUD endpoints and connect a database.
Week 3
Add validation, authentication, authorization, and error handling.
Week 4
Add testing, documentation, pagination, security controls, and deployment.
25. Final Checklist
- Understand REST and HTTP.
- Design consistent resource endpoints.
- Implement CRUD operations.
- Validate request bodies and query parameters.
- Use a database safely.
- Implement authentication and authorization.
- Apply security controls and rate limits.
- Handle errors consistently.
- Document the API.
- Test success and failure cases.
- Deploy with monitoring and backups.
Conclusion
Well-designed REST APIs are predictable, secure, testable, and easy to maintain. Learn the HTTP fundamentals, build a working API, and then improve it with validation, security, documentation, and automated testing.
More guides
- How to Use Codify: A 7-Day Start Plan — New here? Pick a roadmap, make a study plan, start the DSA sheet, revise with notes, practise for placements and test yourself — one step a day, then a daily routine.
- Infosys Preparation Guide: Online Test, Pseudocode and Interview — Roles (SE, DSE, SP), what each section of the Infosys online test checks, how to crack pseudocode and reasoning, a 4-week plan and the interview.
- Wipro Elite NLTH Preparation: Aptitude, Essay and Coding — The Wipro fresher test round by round — quant, logical and verbal, the written essay, two coding problems — plus a 3-week plan and interview tips.
- Accenture Preparation Guide: Cognitive, Technical, Coding and Communication — Every Accenture round explained — cognitive, MS Office/networking/cloud technical MCQs, pseudocode, coding and the spoken-English test — with a 4-week plan.