Authors: @Jacqueline Osborn, @Timothy Ko, @Yousef Ahmed
Last Updated: 3/24/21
REST is a specification that Hack4Impact often uses (as opposed to something like GraphQL) to design APIs - in this doc, we'll go over some of our guidelines when creating REST APIs.
HTTP Request Methods
- GET: Get a collection of resources or a single resource (ex. get all users, get one user). We do not pass a payload, and this must not change anything in the database - it only returns information.
- Status codes: 200 (OK), 404 (Not Found)
- POST: Create a new resource. Also a catch-all function for operations that don't fit into the other functions (e.g. complex query that does not scale well as a GET request).
- Status codes: 201 (Created), 404 (Not Found)
- PUT: Update/replace a specific resource.
- Status codes: 200 (OK), 204 (No Content), 404 (Not Found)
- PATCH: Update/modify a specific resource.
- Status codes: 200 (OK), 204 (No Content), 404 (Not Found)
- DELETE: Delete a specific resource.
- Status codes: 200 (OK), 404 (Not Found)
The difference between PUT and PATCH can be a little confusing on when to use what - I've found this guide to be helpful in explaining the difference.
Similarly, PUT and POST can be confusing in that they are both capable of creating a resource. The difference is, assuming we have a database and an object X
, expected behavior would be if we PUT X
1000 times, we still have one X
object in the database. If we POST X
1000 times, we have 1000 X
objects.
REST URI Naming Conventions
Dos and Don'ts
- Do use plural nouns, with all lowercase letters
Good: /users
Bad: /user
Bad: /getUsers
- Don't use query string parameters for specifying ids
Good: /users/1 // Get user with id 1
Bad: /users?id=1
- Do use query string parameters only for filtering