RESTful API Design Tips from Experience

A working guide of API design tips and trend evaluations.

Versioning

GET www.myservice.com/api/v1/posts
GET api.myservice.com/v1/posts

Cross-Origin Resource Sharing (CORS)

Routes

Use HTTP Methods

Use Plurals

// DO: plurals are consistent and make sense
GET /v1/posts/:id/attachments/:id/comments

// DON'T: is it just one comment? is it a form? etc.
GET /v1/post/:id/attachment/:id/comment

Use Nesting for Relationship Filtering

Use More of your “Route-Space”

Use the Authorisation Context to Filter

Use a “Me” Endpoint

Provide Pagination

“From” Parameter

Next Page Token

Responses

Use Envelopes

// DO: enveloped
{
data: [
{ ... },
{ ... },
// ...
]
}

// DON'T non-enveloped
[
{ ... },
{ ... },
// ...
]
// enveloped, error extraction from payload
const { data, error } = payload
// processing errors if they exist
if (error) { throw ... }
// otherwise
const normalizedData = normalize(data, schema)

JSON Responses and Requests

Return the Updated Object

Use 204 for Deletions

DELETE /v1/posts/:id
// response - 204
{
"data": null
}

Use HTTP Status Codes and Error Responses

for Data Errors

for Auth Errors

for Standard Statuses

Field Validation Errors

POST /v1/register
// request
{
"email": "end@@user.comx"
"password": "abc"
}
// response - 422
{
"error": {
"code": "FIELDS_VALIDATION_ERROR",
"message": "One or more fields raised validation errors."
"fields": {
"email": "Invalid email address.",
"password": "Password too short."
}
}
}

Operational Validation Errors

POST /v1/register
// request
{
"email": "end@user.com",
"password": "password"
}
// response - 409
{
"error": {
"code": "EMAIL_ALREADY_EXISTS",
"message": "An account already exists with this email."
}
}

Authentication

Use Self-extending Session Tokens

Session Creation — Logging In

Session Renewal

Session Management

Session Termination — Logging Out

Avoid Password Composition Rules

Meta

Use a “Health-Check” Endpoint

GET /v1
// response - 200
{
"status": "running",
"version": "fdb1d5e"
}

github/@ptboyer React, UI, API Design and other thoughts