RESTful API explained
What makes API a RESTful API?
Before we start to write our API, it is essential to understand first what we need to do so our API will be REST complaint.
I won’t go in-depth over all of REST principles, and I’ll focus on what’s necessary for our primary example.
REST stands for REpresentation State Transfer. When a client makes an API call, we will transfer a representation of the state of some resource from its source to the client.
The resource will represent our data. In our example, it will be a User from a Users table via JSON representation.
For someone to know how to fetch our resources, we need it to be uniform and consistent. That is how anyone who knows that your API is RESTful will understand how to use it without any guide or instructions.
It’s essential to name our resources correctly, I’ve seen plenty of APIs that were only halfway RESTful, and it raises many questions to an extent where at some point, you don’t know what response you’ll end up getting from the API.
I recommend you to read the REST Resource Naming Guide and follow it.
Let’s remember the following rules:
- A resource can be a singleton or a collection:
For example, “
customers” is a collection resource and “
customer” is a singleton resource (in a banking domain). We can identify “
customers” collection resource using the URI “
/customers”. We can identify a single “
customer” resource using the URI “
- Use nouns to represent resources
RESTful URI should refer to a resource that is a thing (noun) instead of referring to an action (verb) because nouns have properties that verbs do not have.
So what is CRUD?
CRUD stands for Create, Read, Update, Delete.
Those are basic operations that our API must support for all or part of our resources.
If we look at the SQL implementation of CRUD, we will see that we can achieve it by using:
Create - INSERT
Read - SELECT
Update - UPDATE
Delete - DELETE
We can also achieve that with our RESTful API with the corresponding HTTP verbs like so:
Create - POST
Read - GET
Update - PUT
Delete - DELETE
So that’s sums up the CRUD part of our API, but there is more to it, like HTTP response codes you need to support and some more constraints. Again I suggest you go over the HTTP Methods.