What is a REST API
4 Rules (TL;DR
)
- Offer access through resources
- Things; addresses, not instructions per se.
- Represent resources by representations
- One address per thing. (E.g., not per format.)
- Exchange self-descriptive messages
- Stand-alone messages; xfr per standards only (E.g., HTTP methods.)
- Connect resources through links
- All things are addressed, and only by their (unique) hyperlinks.
Representaional State Transfer (REST)
A REST API leverages HTTP request types to indicate the desired action. The characteristics of REST are the four rules of uniform interface:
- Offer access through resources
- Represent resources by representations
- Exchange self-descriptive messages
- Connect resources through links
APIs that follow these rules are REST APIs.
1. Offer access through resources
NOT REST
/changeTodoList.php?item=35&action=changeTitle&title=new_title
Note how this is indeed an instruction: change something. But a “changeTodoList” is not a thing, it's not a resource.
In the REST architectural style, servers only offer resources. Resources are conceptual things about which clients and servers communicate.
REST
/todolists/7/items/35/
This above thing is not a command, it is the address of a resource, a thing. You can then use this address to manipulate the to-do list using standard operations, instead of interface-specific commands.
2. Represent resources by representations
A resource is a thing —and we can describe those things in different formats. For instance, humans might want to see an HTML version, which your browser transforms into a readable layout. But sometimes, interfaces on the Web are used by machines, too. They need a different format, such as JSON.
In a non-REST way, different formats have different addresses:
NOT REST
browser: /showTodoList.php?format=html
application: /showTodoList.php?format=json
The problem is then that systems using different formats cannot communicate with each other, because they use different addresses for the same things!
In a REST system, addresses identify things, not formats, so all systems use the same address for the same thing. How can they get different formats then? They explicitly ask for it! The technique that enables this is called content negotiation; one URI for many formats, "negotiated" per HTTP Headers (Hypermedia APIs
Many interfaces that label themselves as “REST” are actually something else (“HTTP interfaces”), because they don't follow all of the rules.
Rules 2 and 4 are often violated, but it's not entirely uncommon to see rule 1 being violated as well. For those developers, “REST” simple means “we didn't do the XML messages thing”.
REST interfaces that follow all four rules are now often called “hypermedia APIs”, referring to the fourth rule.