# REST API

* Why REST?
* Why JSON?

**Design**

* Base URL
* Resource
* Resource Format
* Content Negotiation
* Query Parameters
* Pagination
* Errors
* Security
* Caching & ETags
* Rate Limiting
* Multi Tenancy
* Maintenance

## HTTP Verbs

Use HTTP Verbs to Make Your Requests Mean Something API consumers are capable of sending `GET`, `POST`, `PUT`, and `DELETE` verbs, which greatly enhance the clarity of a given request. ([source](http://www.restapitutorial.com/lessons/restquicktips.html))

Generally, the four primary HTTP verbs are used as follows:

**GET** Read a specific resource (by an identifier) or a collection of resources.

**PUT** Update a specific resource (by an identifier) or a collection of resources. Can also be used to create a specific resource if the resource identifier is know before-hand.

**DELETE** Remove/delete a specific resource by an identifier.

**POST** Create a new resource. Also a catch-all verb for operations that don't fit into the other categories.

## HTTP Status Codes

Suggested usages for the **"Top 10" HTTP Response Status Codes** are as follows ([source](http://www.restapitutorial.com/lessons/restquicktips.html)):

`200 OK` General success status code. This is the most common code. Used to indicate success.

`201 CREATED` Successful creation occurred (via either POST or PUT). Set the Location header to contain a link to the newly-created resource (on POST). Response body content may or may not be present.

`204 NO CONTENT` Indicates success but nothing is in the response body, often used for DELETE and PUT operations.

`400 BAD REQUEST` General error for when fulfilling the request would cause an invalid state. Domain validation errors, missing data, etc. are some examples.

`401 UNAUTHORIZED` Error code response for missing or invalid authentication token.

`403 FORBIDDEN` Error code for when the user is not authorized to perform the operation or the resource is unavailable for some reason (e.g. time constraints, etc.).

`404 NOT FOUND` Used when the requested resource is not found, whether it doesn't exist or if there was a 401 or 403 that, for security reasons, the service wants to mask.

`405 METHOD NOT ALLOWED` Used to indicate that the requested URL exists, but the requested HTTP method is not applicable. For example, POST /users/12345 where the API doesn't support creation of resources this way (with a provided ID). The Allow HTTP header must be set when returning a 405 to indicate the HTTP methods that are supported. In the previous case, the header would look like "Allow: GET, PUT, DELETE"

`409 CONFLICT` Whenever a resource conflict would be caused by fulfilling the request. Duplicate entries, such as trying to create two customers with the same information, and deleting root objects when cascade-delete is not supported are a couple of examples.

`500 INTERNAL SERVER ERROR` Never return this intentionally. The general catch-all error when the server-side throws an exception. Use this only for errors that the consumer cannot address from their end.

**More Comprehensive HTTP Status Code from** <https://en.wikipedia.org/wiki/List_of_HTTP_status_codes>

`200 OK` - Response to a successful GET, PUT, PATCH or DELETE. Can also be used for a POST that doesn't result in a creation.

`201 Created` - Response to a POST that results in a creation. Should be combined with a Location header pointing to the location of the new resource

`204 No Content` - Response to a successful request that won't be returning a body (like a DELETE request)

`304 Not Modified` - Used when HTTP caching headers are in play

`400 Bad Request` - The request is malformed, such as if the body does not parse

`401 Unauthorized` - When no or invalid authentication details are provided. Also useful to trigger an auth popup if the API is used from a browser

`403 Forbidden` - When authentication succeeded but authenticated user doesn't have access to the resource

`404 Not Found` - When a non-existent resource is requested

`405 Method Not Allowed` - When an HTTP method is being requested that isn't allowed for the authenticated user

`409 Conflict` - Indicates that the request could not be processed because of conflict in the request, such as an edit conflict between multiple simultaneous updates.

`410 Gone` - Indicates that the resource at this end point is no longer available. Useful as a blanket response for old API versions

`415 Unsupported Media Type` - If incorrect content type was provided as part of the request

`422 Unprocessable Entity` - Used for validation errors

`429 Too Many Requests` - When a request is rejected due to rate limiting

`500 Internal Server Error` - A generic error message, given when an unexpected condition was encountered and no more specific message is suitable.\[60]

`501 Not Implemented` - The server either does not recognize the request method, or it lacks the ability to fulfill the request.

`502 Bad Gateway` - The server was acting as a gateway or proxy and received an invalid response from the upstream server.\[62]

`503 Service Unavailable`

## Miscellaneous

### REST API Best practices

#### Where to put parameters?

<http://stackoverflow.com/questions/4024271/rest-api-best-practices-where-to-put-parameters?answertab=votes#tab-top>

Compare: 1. As part of the URL-path (i.e. /api/resource/parametervalue ) 2. As a query argument (i.e. /api/resource?parameter=value )

Designing a REST api by URI vs query string <http://programmers.stackexchange.com/questions/270898/designing-a-rest-api-by-uri-vs-query-string>

## Reference

### Books & Tutorials

* [REST CookBook](http://restcookbook.com/) | [GitHub](https://github.com/restcookbook/restcookbook)
* [Learn REST: A RESTful Tutorial](http://www.restapitutorial.com/)
* [RESTful Service Best Practices](https://github.com/tfredrich/RestApiTutorial.com/raw/master/media/RESTful%20Best%20Practices-v1_2.pdf)

### Articles

* [REST API Quick Tips](http://www.restapitutorial.com/lessons/restquicktips.html)
* [Best Practices for Designing a Pragmatic RESTful API](http://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api)
* [GitHub: restful-api-design-references](https://github.com/aisuhua/restful-api-design-references)
* [Thoughts on RESTful API Design](https://restful-api-design.readthedocs.io/en/latest/)
* [ThoughtWorks: REST API Design - Resource Modeling](https://www.thoughtworks.com/insights/blog/rest-api-design-resource-modeling)

### Slides

* [Design Beautiful REST + JSON APIs](http://www.slideshare.net/stormpath/rest-jsonapis)
* [RESTful API Design, Second Edition](http://www.slideshare.net/apigee/restful-api-design-second-edition)

### Sub Topics

#### Security

* [Best Practices You Must Apply to Secure Your APIs](http://www.slideshare.net/rnewton/best-practices-you-must-apply-to-secure-your-apis)
* [Secure Your REST API (The Right Way)](http://www.slideshare.net/stormpath/secure-your-rest-api-the-right-way)

#### HTTP Status Code

* [HTTP Status Codes](https://httpstatuses.com/)

### Examples

* [Stack Exchange API v2.2](https://api.stackexchange.com/docs)
* [GitHub API v3](https://developer.github.com/v3/)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://aaronice.gitbook.io/study-notes/architecture-and-system-design/2016-03-15-rest-api.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
