Skip to content

Instantly share code, notes, and snippets.

@Dimanaux
Last active March 5, 2020 11:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Dimanaux/60c7893f8ee8b30818a55d682c3144bb to your computer and use it in GitHub Desktop.
Save Dimanaux/60c7893f8ee8b30818a55d682c3144bb to your computer and use it in GitHub Desktop.

Typical REST API design

Use nouns and ids to represent a resource

// OK
/users/1
/galleries/1/photos/23/comments

// prefer plural nouns, since GET /user Should respond with many users

Classic design

GET    /posts    // fetch all posts (you can use params for pagination, sorting and stuff - /posts?page=1)
GET    /posts/1  // fetch signle post with slug = 1
POST   /posts    // create a new post
PUT    /posts/1  // update post #1
PATCH  /posts/1  // the same - update post #1
DELETE /posts/1  // remove post #1

Use HTTP verb to indicate action

// GOOD
POST /users/1/articles
{...}

// BAD
POST /users/1/articles/create
{...}
GET  /users/1/articles/create?...

Common sense

Use custom slugs instead of ids

/users/1 // nah, it's very popular, but not ok for security, it's not readable, memorable
/users/easy_to_remember_username/gallery/vacation-2020 // good!

Use http

Learn about HTTP status codes and use them.

Responses examples

// bad
200 OK
{
  "status": "error",
  "data": {...}
}

// bad
200 OK
{
  "status": "ok",
  "data": {...}
}

// Good
200 OK
{
  "title": "...",
  // data
}

// Good
422 UNPROCESSABLE ENTITY
{
  "errors": {
    "title": "can't be blank"
  }
}

Also use headers from http - Content-Type, Authorization.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment