Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Best Practices for RESTful API Design

Tech 1

Core Principles

RESTful APIs are widely adopted architectural guidelines for designing Web service interfaces, built around three foundational tenets:

  1. Each URI identifies a unique resource
  2. Client-server commmunication exchanges representations of these resources (e.g., JSON, XML)
  3. Clients manipulate resources via four standard HTTP methods to trigger "Representational State Transfer" (REST)

Endpoint Specifications

1. HTTP Methods

Use HTTP verbs to define standard operations on resources, ensuring consistency across your API:

  • GET: Retrieve a single resource or list of resources (safe and idempotent)
  • POST: Create a new resource on the server
  • PUT: Replace an entire existing resource with new data
  • PATCH: Update only specific fields of an existing resource
  • DELETE: Remove a resource from the server

2. Resource Naming (Paths)

Paths (or endpoints) should use nouns to represent resources, avoiding verbs entirely. Examples for a zoo management API:

  • GET /zoos: List all zoos
  • POST /zoos: Add a new zoo
  • GET /zoos/{zoo_id}: Fetch details of a specific zoo
  • PUT /zoos/{zoo_id}: Replace all data for a specific zoo
  • PATCH /zoos/{zoo_id}: Modify selected fields of a specific zoo
  • DELETE /zoos/{zoo_id}: Delete a specific zoo
  • GET /zoos/{zoo_id}/animals: List all animals in a specific zoo
  • DELETE /zoos/{zoo_id}/animals/{animal_id}: Remove a specific animal from a specific zoo

Anti-pattern examples to avoid:

  • /getAllCars
  • /createNewCar
  • /deleteAllRedCars

For complex actions that don’t map directly to standard verbs, model the action as a resource. For instance, instead of POST /accounts/{from_id}/transfer/{amount}/to/{to_id} for bank transfers, use:

POST /transactions HTTP/1.1
Host: api.bank.com
from_account=12345&to_account=67890&amount=500.00

3. API Versioning

Include version numbers in the URL to ensure backward compatibility for existing clients: Example: https://api.zooapi.com/v2/

4. Filtering and Pagination

Provide URL parameters to filter, sort, and paginate large result sets:

  • ?limit=20: Limit returned records to 20
  • ?offset=10: Start returning records from position 11
  • ?page=3&per_page=50: Fetch the 3rd page with 50 records per page
  • ?sort=species&direction=desc: Sort results by species in descending order
  • ?status=active: Filter for active animals only

Redundant parameter-path combinations are acceptable for readability (e.g., GET /zoos/{zoo_id}/animals and GET /animals?zoo_id={zoo_id} serve identical purposes).

5. Status Codes

Use standard HTTP status codes to clearly communicate request outcomes:

  • 1xx (Informational): Reserved for low-level HTTP protocol messaging (rarely used in APIs)
  • 2xx (Success): The request was processed successfully
  • 3xx (Redirection): The client must take additional steps to complete the request
  • 4xx (Client Errors): The request contained invalid data or targeted a non-existent resource
  • 5xx (Server Errors): The server encountered an unexpected issue while processing the request (avoid these whenever possible)

Common status code mappings:

  • 200 OK (GET): Request succeeded, returns requested data (idempotent)
  • 201 Created (POST/PUT/PATCH): Resource created or updated successfully
  • 202 Accepted (*): Request queued for background processing (async tasks)
  • 204 No Content (DELETE): Resource deleted successfully
  • 400 Bad Request (POST/PUT/PATCH): Invalid request syntax or parameters (no server-side state change)
  • 401 Unauthorized (*): Authentication failed (invalid token, credentials, or missing auth)
  • 403 Forbidden (*): Authenticated but not authorized to access the resource
  • 404 Not Found (*): Targeted resource does not exist (no server-side state change)
  • 406 Not Acceptable (GET): Requested response format not supported (e.g., asking for XML when only JSON is available)
  • 410 Gone (GET): Resource was permanently deleted and will not be restored
  • 422 Unprocessable Content (POST/PUT/PATCH): Validation failed while creating/updating a resource
  • 500 Internal Server Error (*): Unexpected server failure
  • 502 Bad Gateway: Invalid resposne from an upstream server
  • 503 Service Unavailable: Server is temporarily unable to handle requests
  • 504 Gateway Timeout: Upstream server took too long to respond

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.