Web API  

RESTful APIs Cheatsheet – A Detailed Guide

Introduction

A RESTful API (Representational State Transfer API) is a way for systems to communicate with each other using standard web protocols, usually HTTP. REST APIs are simple, flexible, and widely used in web development. They allow you to perform operations like reading, creating, updating, and deleting data from a server.

This cheatsheet is for developers who want a quick reference to important REST concepts, operations, and best practices. Each section includes a short definition, a simple code example, and any important point you should remember.

1. REST Basics

  • Definition: REST is a set of rules that defines how web services should work. It uses standard HTTP methods like GET, POST, PUT, DELETE.
  • Important Point: REST is stateless. Each API request must contain all the information needed to understand and process the request.

2. HTTP Methods

Method Purpose Example
GET Read data GET /users
POST Create new data POST /users
PUT Update full data PUT /users/1
PATCH Update partial data PATCH /users/1
DELETE Remove data DELETE /users/1

3. Endpoint Naming (Resources)

  • Definition: Use nouns for resource names, not verbs.
  • ✅ Good: /products, /users/1
  • ❌ Bad: /getUser, /deleteProduct
  • Important Point: Use plural nouns. Keep URLs simple and readable.

4. Path Parameters

  • Definition: Variables in the URL path used to identify specific resources.
  • Example
    GET /users/123
    
    Fetches user with ID 123.
  • Important Point: Use for resource identification, not for filtering or actions.

5. Query Parameters

  • Definition: Used to filter, sort, or paginate data.
  • Example
    GET /products?category=books&sort=price
    
  • Important Point: Use ? to begin query parameters and & to separate multiple values.

6. Request Body

  • Definition: Data sent to the server (usually in JSON) with POST, PUT, or PATCH.
  • Example
    POST /users
    {
      "name": "Alice",
      "email": "[email protected]"
    }
    
  • Important Point: Always set Content-Type: application/json in the header when sending JSON.

7. Response Codes

Code Meaning When to Use
200 OK Request successful
201 Created New resource created (POST)
204 No Content Success, but no data returned
400 Bad Request Missing or invalid input
401 Unauthorized Authentication failed
403 Forbidden No permission
404 Not Found Resource not found
500 Internal Server Error Server crashed or misconfigured

8. Status + Message Format

  • Definition: Return useful status and message in JSON.
  • Example
    {
      "status": "success",
      "message": "User created successfully",
      "data": {
        "id": 1,
        "name": "Alice"
      }
    }
    

9. Authentication

  • Definition: Identify users making requests.
  • Common Method: Use Bearer tokens in headers.
  • Example
    Authorization: Bearer YOUR_TOKEN_HERE
    
  • Important Point: Always use HTTPS to secure data.

10. Pagination

  • Definition: Return data in chunks to avoid large responses.
  • Example
    GET /users?page=2&limit=10
    
  • Important Point: Always include total items or total pages in the response.

11. Versioning

  • Definition: Keep old APIs working while improving new ones.
  • Example
    GET /api/v1/users
    
  • Important Point: Place version in the URL (best practice).

12. Caching

  • Definition: Store copies of responses to reduce server load.
  • Header Example
    Cache-Control: max-age=3600
    
  • Important Point: Use proper cache headers to improve performance without stale data.

13. Idempotency

  • Definition: Repeating the same request gives the same result (for GET, PUT, DELETE).
  • Important Point: POST is not idempotent. PUT and DELETE should be.

14. HATEOAS (Optional)

  • Definition: Hypermedia as the engine of application state. Include links in responses.
  • Example
    {
      "id": 1,
      "name": "Alice",
      "links": [
        { "rel": "self", "href": "/users/1" },
        { "rel": "orders", "href": "/users/1/orders" }
      ]
    }
    

15. Error Handling

  • Definition: Send clear and consistent error messages.
  • Example
    {
      "status": "error",
      "message": "Email is required"
    }
    

16. Rate Limiting

  • Definition: Prevent abuse by limiting how many requests a user can make.
  • Header Example
    X-RateLimit-Limit: 100
    X-RateLimit-Remaining: 10
    

17. Content Negotiation

  • Definition: The client tells the server what format it wants using the Accept header.
  • Example
    Accept: application/json
    
  • Important Point: APIs should support at least application/json. Optionally, also support XML or other formats based on the clients.

18. HTTP Headers (Common Ones)

Header Purpose
Content-Type Format of data sent (e.g., JSON)
Authorization Token or credentials
Accept Expected response format
Cache-Control Caching policies
X-Request-ID Unique ID for tracing/debugging

19. Cross-Origin Resource Sharing (CORS)

  • Definition: A browser security feature that blocks requests from different origins unless explicitly allowed.
  • Server Setup Example
    Access-Control-Allow-Origin: *
    
  • Important Point: Use * for public APIs, and restrict to specific domains for protected APIs.

20. Nested Resources

  • Definition: Used to show a relationship between resources.
  • Example
    GET /users/1/orders
    
    Get all orders for user ID 1.
  • Important Point: Keep nesting levels shallow (2-3 max) to avoid complexity.

21. Sorting and Filtering

  • Definition: Let users fetch relevant data by fields.
  • Example
    GET /products?category=books&sort=price_desc
    
  • Important Point: Avoid hard-coding filters. Use query parameters flexibly.

22. Soft Deletes vs Hard Deletes

  • Soft Delete: Mark the record as deleted without removing it from the database.
  • Hard Delete: Permanently remove the record.
  • Example
    {
      "id": 1,
      "isDeleted": true
    }
    
  • Important Point: Use soft delete for critical or user-generated data.

23. Bulk Operations

  • Definition: Perform operations on multiple items in one request.
  • Example
    POST /users/bulk-delete
    {
      "userIds": [1, 2, 3]
    }
    
  • Important Point: Use when reducing network calls is important.

24. API Throttling

  • Definition: Limits the number of API requests in a time window.
  • Use Case: Prevent abuse and server overload.
  • Example: Allow max 100 requests per hour per user.

25. Logging and Monitoring

  • Definition: Log request data, errors, and usage for debugging and analytics.
  • Best Practice
    • Log request path, status code, response time, and user ID.
    • Use centralized logging tools (e.g., ELK Stack, Loggly).

26. API Documentation (OpenAPI / Swagger)

  • Definition: Provide clear, structured documentation for your API.
  • Tool Example: Swagger UI auto-generates UI from OpenAPI spec.
  • Important Point: Keep documentation versioned with the API.

27. Security Best Practices

Practice Why It Matters
HTTPS only Prevents sniffing or MITM attacks
Input validation Stops injection attacks
Rate limiting Prevents brute force and abuse
Use JWT or OAuth tokens Secure and scalable user auth
Hide server stack headers Prevents attackers from knowing tech

28. Consistent Response Format

  • Definition: Use a common structure for success and errors.
  • Example
    {
      "status": "success",
      "data": {...},
      "error": null
    }
    
  • Important Point: Don’t return raw database errors or stack traces in production.

29. Environment-Based Configurations

  • Definition: Separate development, staging, and production configs.
  • Use Case: Use .env files or config files for base URLs, tokens, DB strings.
  • Important Point: Never hard-code credentials or secrets in source code.

30. API Gateway and Load Balancing (Advanced)

  • Definition: Use a gateway (like Kong, AWS API Gateway) to manage routing, throttling, and logging.
  • Use Case: Large-scale systems where you have multiple services (microservices).
  • Important Point: Helps scale your API, secure it, and make maintenance easier.

Conclusion

RESTful APIs are not just about sending and receiving JSON data. They are about clean design, standard rules, and secure, reliable communication between systems. As your APIs grow in complexity and scale, you must handle edge cases like pagination, rate limiting, authentication, and versioning.