What is a REST API? What makes an API RESTful?
Show the answer
Say this first
REST is an architectural style, not a protocol. A RESTful API exposes resources at URIs and works on them with standard HTTP methods, sends representations such as JSON, and is stateless: every request carries everything the server needs, including authentication. Responses use HTTP status codes and can be cached when marked cacheable.
Go deeper
The constraints (Roy Fielding, 2000)
- Client-server. The client and server evolve separately.
- Stateless. No session context is kept between requests. Each call carries its token or credentials.
- Cacheable. Responses say whether they can be cached.
- Uniform interface. Resources named by URIs, changed through representations, self-descriptive messages.
- Layered system. Proxies and load balancers can sit in between without the client knowing.
- Code on demand is optional and rare in network APIs.
Anatomy of a request
GET /dna/intent/api/v1/network-device?hostname=SW1 HTTP/1.1
Host: catc.example.com
Accept: application/json
X-Auth-Token: eyJ0eXAiOiJKV1Qi...Method, path (resource), query string (filter), headers, and for POST, PUT and PATCH a body.
Anatomy of a response
Status line (HTTP/1.1 200 OK), headers such as Content-Type: application/json, and a body.
They will ask next
What is the difference between the Accept and Content-Type headers?
Acceptsays which formats the client wants back.Content-Typesays what format the body of this message is in. A RESTCONF PATCH, for example, sendsContent-Type: application/yang-data+jsonand oftenAccept: application/yang-data+json.Path parameter or query parameter?
The path names the resource (
/devices/42). The query string filters, sorts or pages a collection (/devices?site=dc1&limit=50).
Traps
- Saying REST means JSON. REST works with any representation; JSON is just the common one.
- Thinking stateless means the server stores nothing. It stores data; it does not keep per-client session state between calls.