RESTful API Design Tips from Experience

A working guide of API design tips and trend evaluations.

Peter Boyer
May 31, 2017 · 13 min read

Versioning

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

Cross-Origin Resource Sharing (CORS)

Routes

Use HTTP Methods

Image for post

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"
}

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store