GuidesRESTful APIs

RESTful APIs Basics

Learn REST principles, HTTP methods, status codes, authentication, and how modern web applications communicate through APIs.

10 minute read Intermediate

What is REST?

REST (Representational State Transfer) is an architectural style for designing web APIs. RESTful APIs use HTTP requests to perform CRUD operations (Create, Read, Update, Delete) on resources.

A REST API treats everything as a resource (users, products, orders) identified by a URL. You interact with resources using standard HTTP methods, making APIs predictable and easy to understand.

Why REST?

REST APIs power most modern web applications. Understanding REST is essential for frontend developers, backend developers, and anyone working with web services.

REST Principles

  • Stateless: Each request contains all information needed; server doesn't remember previous requests
  • Client-Server: Clear separation between frontend and backend
  • Cacheable: Responses can be cached for better performance
  • Uniform Interface: Standard methods and predictable URLs
  • Layered System: Architecture can have multiple layers (proxies, load balancers)

Resource-Oriented Design

Everything is a resource with a unique identifier (URI):

/users/123           → User resource with ID 123
/products/456        → Product resource with ID 456
/orders/789/items    → Items within order 789

HTTP Methods (CRUD Operations)

REST uses HTTP methods to indicate the type of operation:

GET - Read Data

Retrieve data from the server. GET requests should never modify data.

GET /api/users          → Get all users
GET /api/users/123      → Get user with ID 123
GET /api/users?role=admin → Get filtered users
Example Response
HTTP/1.1 200 OK
Content-Type: application/json

{
  "id": 123,
  "name": "John Doe",
  "email": "[email protected]",
  "role": "admin",
  "created_at": "2026-01-01T10:00:00Z"
}

POST - Create Data

Create a new resource. Send data in the request body.

POST /api/users
Content-Type: application/json

{
  "name": "Jane Smith",
  "email": "[email protected]",
  "password": "SecurePass123!"
}

Response: HTTP/1.1 201 Created
Location: /api/users/124

PUT - Update (Replace) Data

Replace an entire resource with new data. All fields required.

PUT /api/users/123
Content-Type: application/json

{
  "name": "John Updated",
  "email": "[email protected]",
  "role": "moderator"
}

PATCH - Update (Modify) Data

Partially update a resource (change only specific fields).

PATCH /api/users/123
Content-Type: application/json

{
  "email": "[email protected]"
}

DELETE - Remove Data

Delete a resource.

DELETE /api/users/123

Response: HTTP/1.1 204 No Content
PUT vs PATCH

PUT: Replaces entire resource (must send all fields)
PATCH: Updates specific fields (send only changed fields)
Example: PUT needs name, email, role; PATCH needs only email

Idempotency

Some methods are idempotent (multiple identical requests have same effect as one):

  • GET, PUT, DELETE: Idempotent
  • POST, PATCH: Not idempotent

API Endpoints & URL Structure

REST APIs use clear, hierarchical URLs to represent resources:

Resource Naming Conventions

/api/resources           → Collection
/api/resources/123       → Specific item
/api/resources/123/items → Nested resource

Real-World Examples

GET    /api/posts           → All blog posts
GET    /api/posts/456       → Post with ID 456
GET    /api/posts/456/comments → Comments on post 456
POST   /api/posts/456/comments → Add comment to post 456
DELETE /api/comments/789    → Delete comment 789
GET    /api/users/123/posts → All posts by user 123

Query Parameters for Filtering

/api/products?category=electronics&sort=price&limit=20
/api/users?active=true&role=admin
/api/orders?status=pending&date_from=2026-01-01&date_to=2026-12-31
/api/search?q=laptop&page=2

Common Query Parameters

  • Pagination: ?page=2&limit=20
  • Sorting: ?sort=created_at&order=desc
  • Filtering: ?status=active&category=tech
  • Search: ?q=search+term
  • Fields: ?fields=id,name,email

HTTP Status Codes

Status codes tell you if the request succeeded and provide error details:

2xx - Success

  • 200 OK: Request succeeded (GET, PUT, PATCH)
  • 201 Created: Resource created successfully (POST)
  • 204 No Content: Success with no response body (DELETE)

4xx - Client Errors

  • 400 Bad Request: Invalid data sent (malformed JSON)
  • 401 Unauthorized: Authentication required or failed
  • 403 Forbidden: Authenticated but no permission
  • 404 Not Found: Resource doesn't exist
  • 409 Conflict: Request conflicts with current state
  • 422 Unprocessable Entity: Validation failed
  • 429 Too Many Requests: Rate limit exceeded

5xx - Server Errors

  • 500 Internal Server Error: Server crashed
  • 502 Bad Gateway: Upstream server error
  • 503 Service Unavailable: Server overloaded/maintenance
  • 504 Gateway Timeout: Upstream server timeout
Error Response Example
HTTP/1.1 422 Unprocessable Entity
Content-Type: application/json

{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Validation failed",
    "details": {
      "email": "Invalid email format",
      "age": "Must be at least 18",
      "password": "Too weak"
    }
  }
}

Authentication & Authorization

1. API Keys

Simple authentication using a secret key:

GET /api/users
X-API-Key: your-secret-key-here

2. Bearer Tokens (JWT)

Most common modern approach:

POST /api/login
Content-Type: application/json

{
  "email": "[email protected]",
  "password": "password123"
}

Response:
{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "expires_in": 3600
}

// Use token in subsequent requests
GET /api/profile
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

3. OAuth 2.0

For third-party access (Google, Facebook login):

1. User clicks "Login with Google"
2. Redirect to Google authorization page
3. User approves access
4. Google redirects back with authorization code
5. Exchange code for access token
6. Use access token to access protected resources

4. Basic Authentication

Authorization: Basic base64(username:password)

// Example: username=admin, password=secret
Authorization: Basic YWRtaW46c2VjcmV0
Security Note

Always use HTTPS for authentication. Never send credentials in URLs. Store tokens securely (HttpOnly cookies, not localStorage).

REST API Best Practices

1. Use Nouns, Not Verbs

✅ GET /api/users
❌ GET /api/getUsers

✅ DELETE /api/posts/123
❌ POST /api/deletePost/123

✅ POST /api/orders
❌ POST /api/createOrder

2. Use Plural Nouns for Collections

✅ /api/users
❌ /api/user

✅ /api/products
❌ /api/product

3. Version Your API

/api/v1/users
/api/v2/users

// Or use headers
Accept: application/vnd.myapi.v1+json

4. Return Appropriate Status Codes

  • Don't return 200 for errors
  • Use 201 for created resources
  • Use 204 for successful deletes
  • Use specific 4xx codes for different client errors

5. Implement Pagination

GET /api/posts?page=2&limit=20

Response:
{
  "data": [...],
  "pagination": {
    "page": 2,
    "limit": 20,
    "total": 150,
    "total_pages": 8,
    "has_next": true,
    "has_prev": true
  },
  "links": {
    "next": "/api/posts?page=3&limit=20",
    "prev": "/api/posts?page=1&limit=20",
    "first": "/api/posts?page=1&limit=20",
    "last": "/api/posts?page=8&limit=20"
  }
}

6. Use HTTPS

Always use HTTPS to encrypt data in transit, especially for authentication tokens and sensitive data.

7. Handle Errors Consistently

{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid input provided",
    "details": { ... },
    "timestamp": "2026-01-07T10:00:00Z",
    "path": "/api/users"
  }
}

8. Rate Limiting

Protect your API from abuse:

HTTP/1.1 429 Too Many Requests
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1704628800
Retry-After: 3600

{
  "error": "Rate limit exceeded. Try again in 1 hour."
}

9. CORS Headers

Allow browser requests from different origins:

Access-Control-Allow-Origin: https://example.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Content-Type, Authorization
API Documentation

Always document your API with:
• OpenAPI/Swagger specification
• Example requests and responses
• Authentication requirements
• Rate limits and error codes

Testing REST APIs

Popular tools for API testing:

  • Postman: GUI for testing APIs, collections, automation
  • cURL: Command-line tool
  • Insomnia: Alternative to Postman
  • HTTPie: User-friendly cURL alternative
  • Browser DevTools: Network tab for debugging
cURL Examples
# GET request
curl https://api.example.com/users

# POST with JSON
curl -X POST https://api.example.com/users \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -d '{"name":"John","email":"[email protected]"}'

# PUT request
curl -X PUT https://api.example.com/users/123 \
  -H "Content-Type: application/json" \
  -d '{"name":"John Updated"}'

# DELETE request
curl -X DELETE https://api.example.com/users/123 \
  -H "Authorization: Bearer YOUR_TOKEN"

Common Mistakes to Avoid

  • ❌ Using GET to modify data
  • ❌ Returning HTML error pages instead of JSON
  • ❌ Not handling authentication errors properly
  • ❌ Exposing internal database IDs without consideration
  • ❌ Not implementing rate limiting
  • ❌ Ignoring CORS for browser requests
  • ❌ Inconsistent error response formats
  • ❌ Not versioning your API
  • ❌ Missing pagination for large collections

REST APIs are the backbone of modern web development. Master these concepts to build scalable, maintainable, and secure web services that follow industry standards. A well-designed API makes integration easy and improves developer experience.