REST is NOT a design pattern
REST is NOT a technology
REST is NOT language/tool/protocol specific.
Then, what is it?
REST stands for REpresentational State Transfer and it is a set of constraints that must be satisfied when building an API before it can be said to be RESTful.
What are the benefits of building APIs that are RESTful?
- Flexibility: can service clients with different needs (file formats etc.)
- Scalability: can scale easily as the traffic increases
- Maintainability: easier to maintain over a long time
How can we build RESTful APIs?
By following the following constraints:
- Client-Server Architecture
- Uniform Interface
- Layered System
- Code on Demand (Optional)
Client-Server Architecture :
- No direct function call leads to separation of concerns
- As long as contract between server and client is untouched, clients and servers can manage their concerns independently as follows:
- Server: performance, scaling, authentication & authorization, data cache control, data security, database
- Client: UX, UI, Multi form factor support.
Don’t reinvent the wheel: use well known standards to define the interface between the server and the client.
- Identification of resources, Use the URL/URI standard in identifying a resource.
- Use Well known protocol standards (preferably HTTP becomes it is the protocol for the world wide web) for server-client communication
- Use standard MIME types, Headers, etc. for self descriptive meta data. This way the client can server can focus on semantics and not worry about specific data-structures on either ends.
- HATEOAS: hypermedia as the state of application state. Use hyperlinks and possible URI templates to decouple the client from the application specific url structure. The links can be annotated with semantics e.g link relations, basically response : data + actions
- No state management (sessions) allowed on the server as done on a typical website.
- All client calls are independent.
- The client sends all the information in the request the server needs to process the request.
- This counterbalances some negative impact by statelessness (performance, high traffic) e.g client retrieving and processing same data with no changes from previous request.
- Responses from the server must be explicitly labelled as cacheable or non-cacheable.
- Examples of cache http headers: Cache-Control, Expires, Last-Modified, Etag
- REST API architectures should consist of layers and no one layer can see past the next, this means every layer can only communicate to the layer in front of it.
- Layers may be added, removed or modified based on needs.
- Client should never connect directly to the App Server (tight coupling and difficult to scale.)
- Examples of layered architecture for REST APIs:
– Client –> Gateway –> App Server –> Database
– Client –> Gateway –> Load Balancer –> App Server –> Database
The last constraint (Code on Demand) is optional and hence we won’t be discussing about it.