Key Takeaways

  1. Use the Appropriate HTTP Method: Determine the operation type and apply the correct HTTP method such as GET, POST, PUT, PATCH, or DELETE.

  2. Use Query Parameters for Filtering, Sorting, and Searching: Incorporate query parameters like filter, sort, and search in request URLs to retrieve precise data.
  3. Use HTTP Response Status Codes: Return appropriate HTTP status codes to clearly communicate the result of each request.
  4. Create API Documentation and Version Your REST APIs: Maintain comprehensive documentation and implement versioning to simplify API adoption and updates
  5. Cross-Origin Resource Sharing (CORS): Enhance security by managing cross-origin HTTP requests through proper CORS configuration.

REST is an architectural style for developing APIs, known for its simplicity and widespread adoption among developers. Many leading software development companies favor REST over other protocols like SOAP when building modern applications.

Today, RESTful APIs and web services are crucial for communication between clients and servers. Therefore, designing robust and efficient APIs is essential. To accomplish this, API developers should adhere to established best practices, some of which are outlined in the blog below.

1. What is a REST API?

A REST API, or Representational State Transfer Application Programming Interface, is a programming style designed to facilitate web architecture development.

REST APIs offer a simple and efficient way for two computers to communicate over HTTP or HTTPS. This process closely mirrors the typical client-server interaction, making it intuitive and effective.

2. Rest API Best Practices

Follow these best practices to maximize the effectiveness of your REST APIs.

2.1 Use JSON to Send and Receive Data

While some believe REST APIs should use hypertext exclusively for data exchange, using JSON for request payloads and responses is highly effective. JSON has become the standard format for data transfer and is widely supported by modern networking technologies.

JavaScript provides built-in methods to encode and decode JSON, whether using an HTTP client or the Fetch API. Similarly, most server-side frameworks offer libraries that easily parse JSON data.

Not all frameworks support XML for data transfer, making JSON essential for converting data into usable information. Although manipulating data in this way can be complex in browsers, JSON is ideal for transferring text and numerical data directly to the client side, whereas form data is better suited for file uploads.

After sending a request, ensure the response header includes Content-Type: application/json so clients correctly interpret the response data. This is the default behavior in many server-side frameworks, where API endpoints return JSON responses. HTTP clients rely on this header to parse the data appropriately.

2.2 Use the Appropriate HTTP Method

After defining an endpoint, it’s important to choose the correct HTTP method based on the operation you want to perform. Here are some common methods and their typical uses:

  • Use GET requests to retrieve resources.

  • Use POST requests to create resources, especially when the server assigns a unique identifier.

  • Use PUT requests to create or completely replace resources.

  • Use PATCH requests to partially update existing resources.

  • Use DELETE requests to remove specified resources.

In this Tweet, APILayer highlights the importance of using the correct HTTP method.

2.3 Use Query Parameters for Filtering, Sorting, and Pagination

To obtain clearer and more precise results, use query parameters such as filter, sort, and search in your HTTP request URLs. These parameters help control the server’s response. Although there’s no strict standard for filtering, sorting, and pagination, these parameters are commonly appended after the endpoint, for example:

  • Filter – Retrieve products by category:
    /products?category={category}

  • Sort – Sort products by price in ascending order:
    /products?sort_by=price

  • Paginate – Get results for a specific page with a defined number of items per page:
    /products?page={page_number}&per_page={results_per_page}

2.4 Use Nouns Instead of Verbs in Endpoints

When designing REST API endpoints, it’s best practice to use nouns rather than verbs in the URL paths. Common HTTP methods such as GET, POST, and DELETE already describe the action, so the endpoint should focus on the resource name.

For instance, instead of using URLs like:
https://myexample.com/getPosts or https://myexample.com/createPost (which include verbs),
use a cleaner, noun-based endpoint like:
https://myexample.com/posts — which implies the GET action for retrieving posts.

Check out this Tweet for more guidance on REST API endpoint naming conventions.

2.5 Use HTTP Response Status Codes

HTTP response status codes indicate the result of an HTTP request and are grouped into five categories:

  • Informational responses (100–199): Provide information to the client.

  • Successful responses (200–299): Indicate that the request was successful.

  • Redirection messages (300–399): Used to redirect the client to a different resource.

  • Client error responses (400–499): Indicate errors caused by the client that need to be addressed.

  • Server error responses (500–599): Indicate errors on the server side, suggesting the client try again later. The exception is error 511, which relates to incorrect user credentials.

2.6 Handle Errors Gracefully and Return Standard Error Codes

When errors occur, they should be handled gracefully by returning standard HTTP status codes that clearly specify the error type. This helps API maintainers and consumers understand and manage issues effectively. Proper error handling is crucial to prevent system failures and to delegate error management to the API consumers.

Below is an example demonstrating user registration, including input validation and returning appropriate HTTP status codes for different error conditions.

Input Validation

When a request body is missing required user details, such as an email ID, the API returns a 400 Bad Request response. This response prompts users to fill in the missing mandatory fields.

User Existence Check

During registration, the API verifies whether the user or any provided details already exist in the database. If a match is found—such as an existing email—the API responds with a 400 Bad Request status and a message like “User already exists.” This informs the user that the email is already registered and asks for a different email to proceed with registration.

Successful Registration

Once all validations pass, the new user is added to the users’ list. The API then returns a success message confirming that the registration was successful for the provided email ID.

Error Messaging Best Practices

Error codes should be accompanied by clear messages that help maintainers diagnose issues, but they should avoid exposing excessive details that attackers might exploit.

In summary, when APIs encounter errors, they should respond gracefully with appropriate status codes and informative—but secure—messages that guide users to resolve the issue.

2.7 Create API Documentation and Version Your REST APIs

Maintaining detailed API documentation is essential to improve adoption and ease of use. Good documentation should cover authentication methods, request and response formats, available endpoints, and other relevant details. A widely used tool for REST API documentation is OpenAPI.

API versioning helps manage updates and changes while ensuring compatibility with existing client applications. Common versioning strategies include:

  • URL versioning: The API version is included directly in the URL, e.g., /api/v1/product indicates version 1.

  • Query parameter versioning: The version is specified as a query parameter, e.g., /api/product?version=1.

  • Header versioning: A custom header carries the version number, e.g., Accept-Version: 1.

  • Content negotiation versioning: The version is negotiated via the media type or Accept header in the request payload.

Versioning ensures API stability, allows developers to adopt changes gradually, and supports backward compatibility.

2.8 Using Path Parameters vs. Query Parameters

When designing APIs, it’s important to distinguish when to use path parameters versus query parameters:

  • Path parameters identify and retrieve specific resources.

  • Query parameters are typically used for filtering, sorting, pagination, or specifying additional options.

Examples:
Path Parameters:
https://api.example.com/orders/789/products/456/reviews

Query Parameters:
https://api.example.com/search?query=books&sort=price&limit=5

2.9 HATEOAS (Hypermedia as the Engine of Application State)

HATEOAS enhances API responses by including metadata and hypermedia links, guiding clients to related actions and resources. This makes your API self-descriptive and improves navigation and discoverability.

By embedding hypermedia links, users can more easily access documentation, perform actions, and explore resources within the API. Despite its benefits, many developers are not familiar with HATEOAS — see this Tweet by Cory House for more insight.