Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

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

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:

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:

  1. A client sends an HTTP request.
  2. The server receives the request.
  3. The server validates the request.
  4. Authentication and authorization are checked when required.
  5. Application logic processes the operation.
  6. The server reads or updates data.
  7. 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

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

Client Errors

Server Errors

Choose status codes consistently and document the meaning of each response.

6. Design Resource URLs

Use nouns that represent resources.

Good examples:

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:

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:

Important practices:

An authenticated user should not automatically gain access to every user's records.

13. API Security

Follow a defense-in-depth approach.

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:

  1. Validate the page and limit.
  2. Enforce a maximum page size.
  3. Allowlist sort fields and sort directions.
  4. Apply filtering and sorting safely.
  5. 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:

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:

Use timeouts, bounded retries, and backoff for transient failures.

18. Rate Limiting

Rate limiting restricts how frequently clients can call an API.

Common strategies:

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:

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:

Test success cases, invalid inputs, missing authentication, forbidden access, nonexistent records, rate limits, and server failures.

21. Deployment and Monitoring

Before deployment:

Do not log access tokens, passwords, or full sensitive request bodies.

22. Common API Design Mistakes

  1. Using incorrect HTTP status codes.
  2. Returning inconsistent response shapes.
  3. Skipping server-side validation.
  4. Exposing private database fields.
  5. Ignoring authorization checks.
  6. Returning every database record in one response.
  7. Exposing stack traces in production.
  8. Retrying unsafe operations without safeguards.
  9. Publishing undocumented breaking changes.
  10. Forgetting rate limits and request size limits.
  11. Failing to test error conditions.
  12. Assuming TypeScript types validate network data.

23. Practical Projects

Beginner

Intermediate

Advanced

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

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