JB logo

Command Palette

Search for a command to run...

yOUTUBE
Blog
PreviousNext

REST API Complete Guide - Professional Developer Training Template | Desishub Technologies

Comprehensive REST API training materials including a 15-slide PowerPoint presentation and detailed markdown documentation. Perfect for teaching developers about RESTful architecture, HTTP methods, authentication, and API best practices. Includes real code examples in Node.js and Python, plus hands-on exercises. Created by JB Web Developer at Desishub Technologies, Uganda's leading custom software development company.

REST API: The Complete Developer's Guide

Author: JB WEB DEVELOPER
Organization: Desishub Technologies
Last Updated: January 2026


Table of Contents

  1. Introduction
  2. Understanding APIs
  3. Why APIs Matter
  4. Real-World API Applications
  5. Types of APIs
  6. Introduction to REST
  7. REST Architectural Principles
  8. HTTP Methods and CRUD Operations
  9. REST URL Structure and Design
  10. Working with REST APIs
  11. HTTP Status Codes
  12. Authentication and Security
  13. Best Practices for REST API Design
  14. Testing and Debugging APIs
  15. Building Your First REST API
  16. Conclusion and Next Steps

Introduction

In today's interconnected digital landscape, Application Programming Interfaces (APIs) serve as the backbone of modern software development. They enable different applications, services, and systems to communicate seamlessly, share data, and work together to deliver complex functionality.

This comprehensive guide will take you through everything you need to know about REST APIs—from fundamental concepts to advanced implementation strategies. Whether you're a beginner taking your first steps into API development or an experienced developer looking to refine your understanding, this guide provides practical insights, real-world examples, and best practices.

What You'll Learn

  • The fundamentals of APIs and why they're essential
  • REST architectural principles and constraints
  • HTTP methods, status codes, and headers
  • URL design patterns and best practices
  • Authentication and security considerations
  • Practical examples in Node.js and Python
  • Testing tools and debugging techniques
  • Advanced topics like rate limiting, caching, and versioning

Understanding APIs

What is an API?

An API (Application Programming Interface) is a set of rules, protocols, and tools that defines how software components should interact with each other. Think of an API as a contract between different software systems that specifies:

  • What requests can be made
  • How to make those requests
  • What data formats to use
  • What responses to expect

The Restaurant Analogy

To understand APIs better, imagine a restaurant:

  • You (the client) sit at a table and want to order food
  • The kitchen (the server) prepares the food but isn't directly accessible to customers
  • The waiter (the API) takes your order, communicates it to the kitchen, and brings back your food

The waiter (API) provides a standard interface between you and the kitchen. You don't need to know how the kitchen operates internally; you just need to know how to order from the menu. Similarly, when you use an API, you don't need to understand the internal workings of the service—you just need to know how to make requests and interpret responses.

How APIs Work

The typical API workflow follows this pattern:

  1. Client Application sends a request to the API endpoint
  2. API receives the request and validates it
  3. API processes the request (may involve database queries, business logic, etc.)
  4. API formats the response according to the agreed-upon format
  5. Client Application receives and processes the response

This communication happens over the internet using standard protocols, most commonly HTTP/HTTPS.


Why APIs Matter

APIs have become essential in modern software development for several compelling reasons:

1. Integration and Interoperability

APIs enable different systems to work together seamlessly, regardless of the technologies they're built with. A mobile app built in Swift can communicate with a backend server written in Python, which in turn can interact with a payment service built in Java.

Example: When you book a flight through a travel website, that site uses multiple APIs to:

  • Search for available flights from different airlines
  • Check seat availability in real-time
  • Process your payment through a payment gateway
  • Send you confirmation emails via an email service API

2. Code Reusability

Once you build an API, it can be consumed by multiple applications across different platforms:

  • Web applications
  • Mobile apps (iOS and Android)
  • Desktop applications
  • Internet of Things (IoT) devices
  • Third-party integrations

Example: Facebook's API allows the same user authentication and social sharing functionality to work across:

  • Facebook's own web and mobile apps
  • Third-party apps that offer "Login with Facebook"
  • Games that post achievements to timelines
  • Business tools that analyze page engagement

3. Development Efficiency

APIs dramatically accelerate development by allowing developers to leverage existing services rather than building everything from scratch.

Example: Building a food delivery app, you can use:

  • Google Maps API for location services and routing
  • Stripe API for payment processing
  • Twilio API for SMS notifications
  • SendGrid API for email receipts

This approach lets you focus on your core business logic rather than reinventing the wheel.

4. Security and Access Control

APIs provide a controlled gateway to your data and services. Instead of giving direct access to your database or internal systems, APIs allow you to:

  • Define exactly what data can be accessed
  • Control who can access it (through authentication)
  • Limit what actions can be performed (through authorization)
  • Monitor and log all access attempts
  • Implement rate limiting to prevent abuse

5. Scalability

Well-designed APIs make it easier to scale applications. You can:

  • Scale the API layer independently from client applications
  • Add caching layers to reduce server load
  • Implement load balancing across multiple servers
  • Distribute API endpoints geographically for better performance
  • Upgrade backend systems without affecting clients (as long as the API contract remains the same)

6. Modularity and Maintainability

APIs promote separation of concerns by dividing complex systems into manageable, independent components.

Example: An e-commerce platform might have separate APIs for:

  • User management
  • Product catalog
  • Shopping cart
  • Order processing
  • Payment handling
  • Inventory management

Each API can be developed, deployed, and scaled independently.


Real-World API Applications

APIs power the digital experiences we use every day. Here are some prominent examples:

Payment Processing

Examples: Stripe, PayPal, Square

Modern payment APIs handle the complexity of financial transactions, including:

  • Credit card processing
  • Bank transfers
  • Recurring subscriptions
  • Multi-currency support
  • Fraud detection
  • PCI compliance

Why it matters: These APIs allow businesses to accept payments without storing sensitive card data, handling complex security requirements, or dealing with banking regulations directly.

Maps and Location Services

Examples: Google Maps API, Mapbox, HERE Maps

Location APIs provide:

  • Geocoding (converting addresses to coordinates)
  • Reverse geocoding (converting coordinates to addresses)
  • Route calculation and optimization
  • Real-time traffic information
  • Place search and details
  • Street view imagery

Real-world use: Uber uses mapping APIs to:

  • Show driver and rider locations in real-time
  • Calculate optimal routes
  • Estimate arrival times
  • Provide turn-by-turn navigation for drivers

Social Authentication

Examples: OAuth APIs from Google, Facebook, GitHub, Twitter

Social login APIs enable:

  • Single sign-on (SSO) experiences
  • Reduced friction in user registration
  • Access to user profile information
  • Social graph connections
  • Sharing capabilities

Weather Data

Examples: OpenWeather, WeatherAPI

Weather APIs provide:

  • Current weather conditions
  • Hourly and daily forecasts
  • Historical weather data
  • Severe weather alerts
  • Air quality information

Email and Communication

Examples: SendGrid, Mailchimp, Twilio

Communication APIs handle:

  • Transactional emails (receipts, confirmations, password resets)
  • Marketing campaigns
  • SMS messaging
  • Voice calls
  • Video conferencing

Types of APIs

While this guide focuses on REST, it's important to understand the API landscape and how REST compares to other approaches.

REST (Representational State Transfer)

Market Share: ~80% of public APIs

Characteristics:

  • Uses standard HTTP methods (GET, POST, PUT, DELETE)
  • Stateless communication
  • Resource-based URLs
  • Typically returns JSON or XML
  • Widely adopted and well-understood

Best for:

  • Public APIs
  • Mobile applications
  • Web services
  • Microservices architectures

Pros:

  • Simple and intuitive
  • Cacheable
  • Language and platform independent
  • Excellent tooling and community support

Cons:

  • Can be chatty (multiple requests needed for related data)
  • Over-fetching or under-fetching data
  • Versioning can be challenging

SOAP (Simple Object Access Protocol)

Market Share: Declining, but still used in enterprise

Characteristics:

  • XML-based protocol
  • Built-in error handling
  • Strict standards (WSDL contracts)
  • Support for complex operations
  • Built-in security (WS-Security)

Best for:

  • Banking and financial systems
  • Enterprise applications
  • Government services
  • Systems requiring ACID transactions

Pros:

  • Comprehensive security features
  • Built-in retry logic
  • Standardized error handling

Cons:

  • Verbose and complex
  • Slower than REST
  • Steeper learning curve

GraphQL

Market Share: Rapidly growing

Characteristics:

  • Query language for APIs
  • Request exactly the data you need
  • Single endpoint for all requests
  • Strongly typed schema
  • Real-time subscriptions

Best for:

  • Complex data requirements
  • Mobile applications (reduce bandwidth)
  • Rapidly evolving frontends
  • Applications with multiple clients

Pros:

  • No over-fetching or under-fetching
  • Single request for complex data
  • Strong typing
  • Excellent developer experience

Cons:

  • Complex caching
  • Potential for expensive queries
  • Steeper learning curve

gRPC

Market Share: Growing in microservices environments

Characteristics:

  • Uses Protocol Buffers (binary serialization)
  • HTTP/2 based
  • Bi-directional streaming
  • Language-agnostic
  • Code generation from schemas

Best for:

  • Microservices communication
  • Real-time applications
  • Low-latency requirements
  • Polyglot environments

Pros:

  • Extremely fast
  • Efficient binary format
  • Streaming support

Cons:

  • Not human-readable
  • Limited browser support
  • Smaller community than REST

Introduction to REST

What is REST?

REST (Representational State Transfer) is an architectural style for designing networked applications, introduced by Roy Fielding in his doctoral dissertation in 2000. It's not a protocol or a standard, but rather a set of architectural constraints that, when applied correctly, create scalable, performant, and maintainable web services.

The Core Concept

REST treats everything as a resource—any piece of information that can be named and accessed. Resources are:

  • Identifiable: Each resource has a unique identifier (URI)
  • Manipulable: Resources can be created, read, updated, and deleted
  • Representable: Resources can be represented in different formats (JSON, XML, HTML)
  • Self-descriptive: Messages include enough information to describe how to process them

Examples of resources:

  • A user: /users/123
  • A blog post: /posts/456
  • A collection of products: /products
  • An order: /orders/789
  • A comment on a post: /posts/456/comments/12

Key Characteristics of REST

1. Stateless Communication

Each request from client to server must contain all information needed to understand and process the request. The server doesn't store any client context between requests.

Benefits:

  • Improved scalability (no session management overhead)
  • Better reliability (no session data to lose)
  • Easier to cache
  • Simplified server design

2. Resource-Based

REST APIs are organized around resources, not actions. URLs represent resources (nouns), and HTTP methods represent actions (verbs).

Good:

GET    /users           # Get all users
GET    /users/123       # Get user 123
POST   /users           # Create new user
PUT    /users/123       # Update user 123
DELETE /users/123       # Delete user 123

Bad:

GET    /getUsers
POST   /createUser
POST   /updateUser/123
POST   /deleteUser/123

3. Client-Server Architecture

REST enforces a clear separation between the client (user interface) and server (data storage/business logic).

Benefits:

  • Independent evolution of client and server
  • Multiple client types can use the same API
  • Improved scalability
  • Simplified architecture

4. Cacheable

Responses must explicitly indicate whether they can be cached, improving:

  • Performance (fewer server requests)
  • Scalability (reduced server load)
  • Network efficiency (reduced bandwidth usage)

REST Architectural Principles

Roy Fielding defined six constraints that define a truly RESTful architecture:

1. Client-Server Architecture

Clear separation of concerns between the user interface (client) and data storage (server).

Benefits:

  • UI can be rewritten without changing the backend
  • Different UIs can cater to different user needs
  • Teams can work independently

2. Statelessness

The server doesn't maintain any client state between requests. Each request is complete and self-contained.

What goes in each request:

  • Authentication credentials (usually in headers)
  • All necessary parameters
  • Resource identifiers
  • Client preferences

3. Cacheability

Responses must define whether they can be cached and for how long.

Cache Control Headers:

Cache-Control: public, max-age=3600
Cache-Control: private, no-cache
ETag: "33a64df551425fcc55e4d42a148795d9f25f89d4"

4. Uniform Interface

All REST APIs follow the same patterns and conventions, making them predictable and easy to use.

The four constraints:

  • Resource identification (unique URIs)
  • Resource manipulation through representations
  • Self-descriptive messages
  • HATEOAS (Hypermedia as the Engine of Application State)

5. Layered System

The client cannot tell whether it's connected directly to the end server or an intermediary.

Example layers:

Client
  ↓
API Gateway
  ↓
Load Balancer
  ↓
Cache Layer
  ↓
API Servers
  ↓
Database

6. Code on Demand (Optional)

Servers can temporarily extend client functionality by transferring executable code (rarely used in modern REST APIs).


HTTP Methods and CRUD Operations

HTTP methods (also called verbs) define the type of action to perform on a resource. REST APIs map these methods to CRUD (Create, Read, Update, Delete) operations.

GET - Retrieve Resources

Purpose: Fetch data from the server without modifying anything.

Characteristics:

  • Repeatable: Yes (calling GET multiple times returns the same data)
  • Safe: Yes (doesn't modify server state)
  • Cacheable: Yes

Examples:

Get a single resource:

GET /api/users/123 HTTP/1.1
Authorization: Bearer eyJhbGc...
 
Response: 200 OK
{
  "id": 123,
  "name": "John Doe",
  "email": "john@example.com"
}

Get a collection with filtering:

GET /api/users?role=admin&status=active HTTP/1.1
 
Response: 200 OK
{
  "data": [
    {"id": 123, "name": "John Doe"},
    {"id": 124, "name": "Jane Smith"}
  ],
  "total": 2
}

POST - Create Resources

Purpose: Create a new resource on the server.

Characteristics:

  • Repeatable: No (each call creates a new resource)
  • Safe: No (modifies server state)
  • Request Body: Required (contains resource data)

Example:

POST /api/users HTTP/1.1
Content-Type: application/json
 
{
  "name": "Jane Smith",
  "email": "jane@example.com",
  "role": "developer"
}
 
Response: 201 Created
Location: /api/users/124
{
  "id": 124,
  "name": "Jane Smith",
  "email": "jane@example.com",
  "created_at": "2026-01-04T10:00:00Z"
}

PUT - Replace Resources

Purpose: Replace an entire resource with new data.

Characteristics:

  • Repeatable: Yes (same request produces same result)
  • Safe: No (modifies server state)
  • Request Body: Required (complete resource representation)

Example:

PUT /api/users/123 HTTP/1.1
Content-Type: application/json
 
{
  "name": "John Doe Updated",
  "email": "john.updated@example.com",
  "role": "senior-developer"
}
 
Response: 200 OK
{
  "id": 123,
  "name": "John Doe Updated",
  "email": "john.updated@example.com",
  "updated_at": "2026-01-04T11:00:00Z"
}

PATCH - Partial Updates

Purpose: Update only specific fields of a resource.

Characteristics:

  • Repeatable: Not always (depends on implementation)
  • Safe: No
  • Request Body: Required (partial resource data)

Example:

PATCH /api/users/123 HTTP/1.1
Content-Type: application/json
 
{
  "email": "newemail@example.com"
}
 
Response: 200 OK
{
  "id": 123,
  "name": "John Doe",              // Unchanged
  "email": "newemail@example.com", // Updated
  "updated_at": "2026-01-04T12:00:00Z"
}

DELETE - Remove Resources

Purpose: Delete a resource from the server.

Characteristics:

  • Repeatable: Yes (deleting already-deleted resource succeeds)
  • Safe: No

Example:

DELETE /api/users/123 HTTP/1.1
Authorization: Bearer eyJhbGc...
 
Response: 204 No Content

Understanding "Repeatable" (Idempotent)

An operation is repeatable if calling it multiple times produces the same result:

# First call
DELETE /api/users/123
Response: 204 No Content (user deleted)
 
# Second call (same request)
DELETE /api/users/123
Response: 204 No Content (still succeeds)
 
# Both successful = Repeatable

Why it matters:

  • Network failures can cause retries
  • Repeatable operations are safe to retry
  • Non-repeatable operations (POST) need special handling

REST URL Structure and Design

A well-designed URL structure makes your API intuitive, discoverable, and maintainable.

Anatomy of a REST URL

https://api.example.com/v1/users/123/posts?status=published

[1]    [2]             [3][4]    [5] [6]           [7]
  1. Protocol: https:// (always use HTTPS)
  2. Domain: api.example.com
  3. Version: /v1
  4. Resource: /users
  5. Identifier: /123
  6. Sub-resource: /posts
  7. Query Parameters: ?status=published

Resource Naming Conventions

1. Use Nouns, Not Verbs

Good:

GET    /users
POST   /users
GET    /users/123
PUT    /users/123

Bad:

GET    /getUsers
POST   /createUser

2. Use Plural Nouns

Good:

/users
/products
/orders

Bad:

/user
/product

3. Use Lowercase and Hyphens

Good:

/product-categories
/user-preferences

Bad:

/ProductCategories
/user_preferences

4. Use Resource Hierarchy

Show relationships through URL structure:

/users/123/posts          # Posts by user 123
/posts/456/comments       # Comments on post 456
/categories/789/products  # Products in category 789

Query Parameters

Query parameters are used for:

  • Filtering
  • Sorting
  • Pagination
  • Searching

Filtering:

/users?role=admin
/products?category=electronics&price_min=100

Sorting:

/users?sort=name           # Ascending
/users?sort=-created_at    # Descending (note the minus)

Pagination:

/users?page=2&per_page=20
/users?offset=20&limit=20

Searching:

/products?search=laptop
/users?q=john

API Versioning

Versioning allows you to evolve your API without breaking existing clients.

URL Versioning (Most Common):

https://api.example.com/v1/users
https://api.example.com/v2/users

When to increment version:

  • Breaking changes (removing fields, changing response structure)
  • Major functionality changes
  • Authentication method changes

Working with REST APIs

Making API Requests

Using cURL (Command Line):

# GET request
curl https://api.example.com/v1/users
 
# POST with JSON
curl -X POST https://api.example.com/v1/users \
     -H "Content-Type: application/json" \
     -H "Authorization: Bearer TOKEN" \
     -d '{"name":"John","email":"john@example.com"}'
 
# DELETE request
curl -X DELETE https://api.example.com/v1/users/123 \
     -H "Authorization: Bearer TOKEN"

Using JavaScript (Fetch API):

// GET request
const getUser = async (userId) => {
  const response = await fetch(`https://api.example.com/v1/users/${userId}`, {
    headers: {
      Authorization: "Bearer YOUR_TOKEN",
    },
  });
  return await response.json();
};
 
// POST request
const createUser = async (userData) => {
  const response = await fetch("https://api.example.com/v1/users", {
    method: "POST",
    headers: {
      Authorization: "Bearer YOUR_TOKEN",
      "Content-Type": "application/json",
    },
    body: JSON.stringify(userData),
  });
  return await response.json();
};

Using Python (requests library):

import requests
 
# GET request
response = requests.get(
    'https://api.example.com/v1/users/123',
    headers={'Authorization': 'Bearer YOUR_TOKEN'}
)
user = response.json()
 
# POST request
response = requests.post(
    'https://api.example.com/v1/users',
    headers={'Authorization': 'Bearer YOUR_TOKEN'},
    json={'name': 'John', 'email': 'john@example.com'}
)
new_user = response.json()

HTTP Status Codes

HTTP status codes provide immediate feedback about the result of an operation.

Status Code Categories

2xx - Success

  • 200 OK - Standard success response
  • 201 Created - Resource successfully created
  • 204 No Content - Success, but no response body

3xx - Redirection

  • 301 Moved Permanently - Resource permanently moved
  • 304 Not Modified - Resource hasn't changed (cache is valid)

4xx - Client Errors

  • 400 Bad Request - Invalid request data/format
  • 401 Unauthorized - Authentication required or failed
  • 403 Forbidden - Authenticated but not authorized
  • 404 Not Found - Resource doesn't exist
  • 409 Conflict - Request conflicts with current state
  • 422 Unprocessable Entity - Validation errors
  • 429 Too Many Requests - Rate limit exceeded

5xx - Server Errors

  • 500 Internal Server Error - Generic server error
  • 502 Bad Gateway - Invalid response from upstream
  • 503 Service Unavailable - Server temporarily unavailable

When to Use Each Code

200 OK:

GET /users/123
Response: 200 OK
{
  "id": 123,
  "name": "John Doe"
}

201 Created:

POST /users
Response: 201 Created
Location: /users/123
{
  "id": 123,
  "name": "John Doe"
}

400 Bad Request:

POST /users
{
  "name": "Jo",  // Too short
  "email": "invalid"
}
 
Response: 400 Bad Request
{
  "error": {
    "code": "VALIDATION_ERROR",
    "details": [
      {"field": "name", "message": "Name must be at least 3 characters"},
      {"field": "email", "message": "Invalid email format"}
    ]
  }
}

404 Not Found:

GET /users/99999
 
Response: 404 Not Found
{
  "error": {
    "code": "RESOURCE_NOT_FOUND",
    "message": "User with ID 99999 not found"
  }
}

Authentication and Security

Security is paramount in API design.

Authentication Methods

1. API Keys

Simple token passed in header:

GET /users HTTP/1.1
Authorization: ApiKey abc123xyz456

Pros:

  • Simple to implement
  • Good for server-to-server

Cons:

  • Less secure (no expiration)
  • Difficult to rotate

2. JSON Web Tokens (JWT)

Self-contained tokens that encode user information:

# Login
POST /auth/login
{
  "email": "user@example.com",
  "password": "password123"
}
 
Response: 200 OK
{
  "access_token": "eyJhbGc...",
  "expires_in": 900
}
 
# Use token
GET /users/me
Authorization: Bearer eyJhbGc...

JWT Structure:

header.payload.signature
eyJhbGc... (Header: algorithm)
eyJ1c2Vy... (Payload: user data, expiration)
SflKxw... (Signature: verification)

Pros:

  • Stateless
  • Self-contained
  • Scalable
  • Industry standard

Cons:

  • Cannot be revoked before expiration
  • Larger than simple tokens

3. OAuth 2.0

Industry standard for authorization, used for third-party access:

User clicks "Login with Google"
  ↓
Redirect to Google
  ↓
User approves
  ↓
Google redirects back with code
  ↓
Exchange code for access token
  ↓
Use token to access Google APIs

Use cases:

  • "Login with Google/Facebook/GitHub"
  • Third-party app integrations
  • Delegated access

Security Best Practices

1. Always Use HTTPS

https://api.example.com  ✅
http://api.example.com   ❌

2. Validate All Input

// Never trust client data
if (!email || !isValidEmail(email)) {
  return 400; // Bad Request
}

3. Use Proper Authentication Headers

# Good
Authorization: Bearer eyJhbGc...
 
# Bad (logged, cached, visible)
GET /users?token=eyJhbGc...

4. Implement Rate Limiting

X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1735689600

5. Handle Errors Securely

// Bad - Exposes too much
{
  "error": "Database connection failed at 192.168.1.100:5432"
}
 
// Good - Generic but helpful
{
  "error": "An error occurred. Please try again later.",
  "request_id": "req_abc123"
}

Best Practices for REST API Design

1. Use Nouns for Resources

/users
/getUsers

2. Use Plural Nouns

/users/123
/user/123

3. Version Your API

/v1/users
/v2/users

4. Use Proper HTTP Status Codes

201 Created for new resources
200 OK for everything

5. Implement Filtering and Pagination

/users?role=admin&page=2&per_page=20

6. Handle Errors Consistently

{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid input",
    "details": [{ "field": "email", "message": "Invalid format" }]
  }
}

7. Use HTTPS Everywhere

All production APIs must use HTTPS to encrypt data in transit.

8. Document Your API

Use tools like Swagger/OpenAPI to create comprehensive, interactive documentation.

{
  "id": 123,
  "name": "John",
  "_links": {
    "self": "/users/123",
    "posts": "/users/123/posts"
  }
}

10. Support Multiple Data Formats

Accept: application/json
Accept: application/xml

Testing and Debugging APIs

Testing Tools

1. Postman

  • Most popular GUI tool
  • Collection organization
  • Automated testing
  • Environment variables
  • Team collaboration

2. Insomnia

  • Clean, modern interface
  • GraphQL support
  • Plugin system

3. cURL

  • Command-line tool
  • Great for automation
  • Available everywhere

4. Swagger UI

  • Interactive documentation
  • Try-it-out functionality
  • Auto-generated from spec

5. HTTPie

  • User-friendly CLI
  • Better syntax than cURL
  • JSON support

Debugging Techniques

Check Request/Response:

curl -v https://api.example.com/v1/users

Validate JSON:

cat response.json | jq .

Test Authentication:

# Without auth (should fail)
curl https://api.example.com/v1/users
# Expected: 401
 
# With auth
curl -H "Authorization: Bearer TOKEN" \
     https://api.example.com/v1/users
# Expected: 200

Building Your First REST API

Node.js + Express Example

Setup:

npm init -y
npm install express jsonwebtoken

Basic Server (app.js):

const express = require("express");
const app = express();
 
app.use(express.json());
 
// In-memory storage
let users = [];
let nextId = 1;
 
// GET /users
app.get("/api/v1/users", (req, res) => {
  res.json({ data: users });
});
 
// GET /users/:id
app.get("/api/v1/users/:id", (req, res) => {
  const user = users.find((u) => u.id === parseInt(req.params.id));
  if (!user) {
    return res.status(404).json({
      error: { message: "User not found" },
    });
  }
  res.json(user);
});
 
// POST /users
app.post("/api/v1/users", (req, res) => {
  const { name, email } = req.body;
 
  if (!name || !email) {
    return res.status(400).json({
      error: { message: "Name and email are required" },
    });
  }
 
  const user = {
    id: nextId++,
    name,
    email,
    created_at: new Date().toISOString(),
  };
 
  users.push(user);
 
  res.status(201).location(`/api/v1/users/${user.id}`).json(user);
});
 
// PUT /users/:id
app.put("/api/v1/users/:id", (req, res) => {
  const index = users.findIndex((u) => u.id === parseInt(req.params.id));
  if (index === -1) {
    return res.status(404).json({
      error: { message: "User not found" },
    });
  }
 
  const { name, email } = req.body;
  users[index] = {
    ...users[index],
    name,
    email,
    updated_at: new Date().toISOString(),
  };
 
  res.json(users[index]);
});
 
// DELETE /users/:id
app.delete("/api/v1/users/:id", (req, res) => {
  const index = users.findIndex((u) => u.id === parseInt(req.params.id));
  if (index === -1) {
    return res.status(404).json({
      error: { message: "User not found" },
    });
  }
 
  users.splice(index, 1);
  res.status(204).send();
});
 
const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

Testing:

# Create user
curl -X POST http://localhost:3000/api/v1/users \
  -H "Content-Type: application/json" \
  -d '{"name":"John","email":"john@example.com"}'
 
# Get all users
curl http://localhost:3000/api/v1/users
 
# Get single user
curl http://localhost:3000/api/v1/users/1
 
# Update user
curl -X PUT http://localhost:3000/api/v1/users/1 \
  -H "Content-Type: application/json" \
  -d '{"name":"John Updated","email":"john.new@example.com"}'
 
# Delete user
curl -X DELETE http://localhost:3000/api/v1/users/1

Conclusion and Next Steps

REST APIs have become the standard for web services due to their simplicity, scalability, and wide adoption. By following the principles and best practices outlined in this guide, you can design and build APIs that are intuitive, scalable, maintainable, and secure.

Key Takeaways

  1. REST is an architectural style, not a protocol. Follow its principles but adapt to your needs.

  2. Use HTTP methods correctly: GET for reading, POST for creating, PUT/PATCH for updating, DELETE for removing.

  3. Design URLs as resources, not actions. Use nouns, not verbs.

  4. Status codes matter. Use them correctly to communicate results clearly.

  5. Version your API from the start. Breaking changes are inevitable.

  6. Security is not optional. Always use HTTPS, implement proper authentication, and validate all input.

  7. Document everything. Good documentation is as important as good code.

  8. Think about your clients. Provide filtering, pagination, and helpful error messages.

Next Steps for Learning

For Beginners:

  1. Build a simple CRUD API with your preferred framework
  2. Practice with public APIs (GitHub, JSONPlaceholder)
  3. Learn about HTTP and how the web works
  4. Study REST principles in depth

For Intermediate Developers:

  1. Implement authentication and authorization
  2. Add rate limiting and caching
  3. Write comprehensive API tests
  4. Create OpenAPI/Swagger documentation
  5. Deploy your API to a cloud platform

For Advanced Developers:

  1. Implement microservices architecture
  2. Explore GraphQL as an alternative
  3. Build API gateways
  4. Optimize for high performance
  5. Set up monitoring and analytics

Free Resources for Practice

Public APIs:

  • JSONPlaceholder - Fake REST API for testing
  • GitHub API - Real-world example
  • OpenWeather API - Weather data
  • REST Countries - Country information

Frameworks:

  • Node.js: Express.js, Fastify, NestJS
  • Python: Flask, FastAPI, Django REST Framework
  • Java: Spring Boot
  • Ruby: Ruby on Rails
  • PHP: Laravel
  • Go: Gin, Echo

Documentation Tools:

  • Swagger/OpenAPI
  • Postman Documentation
  • API Blueprint

Prepared by JB WEB DEVELOPER
Desishub Technologies

Document Version: 1.0
Last Updated: January 2026


Appendix: Quick Reference

HTTP Status Codes

CodeNameUse Case
200OKSuccess
201CreatedResource created
204No ContentSuccess, no body
400Bad RequestInvalid data
401UnauthorizedAuth required
403ForbiddenNot authorized
404Not FoundResource missing
422UnprocessableValidation failed
429Too Many RequestsRate limited
500Internal ErrorServer error

Common HTTP Headers

Request:

  • Authorization - Auth credentials
  • Content-Type - Request format
  • Accept - Response format
  • User-Agent - Client info

Response:

  • Content-Type - Response format
  • Cache-Control - Caching rules
  • Location - New resource URI
  • X-RateLimit-* - Rate limits

REST URL Patterns

# Resources
GET    /users              # List
POST   /users              # Create
GET    /users/123          # Get one
PUT    /users/123          # Replace
PATCH  /users/123          # Update
DELETE /users/123          # Delete

# Nested resources
GET    /users/123/posts    # User's posts

# Filtering
GET    /users?role=admin   # Filter

# Pagination
GET    /users?page=2       # Page 2

# Sorting
GET    /users?sort=-name   # Desc name

End of Document