RESTful API design

2 min read

Designing APIs that are intuitive, consistent and easy to use is crucial. REST (Representational State Transfer) is an architectural style that provides guidelines for creating such APIs.

Resource-based naming

URIs should identify resources, and plural nouns should be used for resource names. For example, /api/products and /api/users/{userId}/orders.

HTTP methods for operations

Use the standard HTTP methods (verbs) to indicate the action to perform on a resource:

Method Use Idempotency
GET Retrieve a resource or a collection of resources. Should be safe and idempotent.
POST Create a new resource. Typically not idempotent.
PUT Update or replace an existing resource completely. Should be idempotent.
PATCH Partially update an existing resource. May or may not be idempotent.
DELETE Remove a resource. Should be idempotent.

HTTP status codes

Use appropriate HTTP status codes to communicate the outcome of a request clearly to the client:

  • Success: 200 OK, 201 Created, 204 No Content
  • Client errors: 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found
  • Server errors: 500 Internal Server Error

Request and response formats

JSON is the de facto standard for request and response payloads in modern Web APIs, because of its simplicity and wide support. Use Data Transfer Objects (DTOs) to shape the data exchanged through the API. That decouples the API contract from internal domain models or database entities. It gives flexibility, and prevents unintended exposure of internal structures.

Filtering, sorting and pagination

For collections of resources, give clients a way to filter, sort and paginate the results using query parameters. For example, /api/products?status=active&sort=-price&page=2&pageSize=25.

HATEOAS

HATEOAS (Hypermedia as the Engine of Application State) means including links in API responses that guide the client to related resources or possible next actions. It makes the API more self-discoverable. It also lets the server evolve the API’s URI structure without breaking clients that follow those links. HATEOAS can add complexity, but it promotes true RESTfulness and loose coupling, which is highly beneficial for long-lived, evolvable APIs.

Security

Always use HTTPS to encrypt communication. Implement robust authentication (verifying client identity, for example OAuth 2.0, OpenID Connect or JWT Bearer tokens) and authorization (determining whether the authenticated client has permission to perform the requested action).

Versioning has its own noteAPI versioningFour ways to let old clients keep working while the API changes.Opens in a new tab.


Sources