Three months ago I’ve chosen a REST architecture for designing my new project at work. The project goal is to create API for managing gyms, trainings and trainees.
This article is just light intro to the REST world, don’t expect cool tips & tricks (maybe in next article).
HTTP request methods
REST without using proper HTTP methods is a nonsense. There are about 9 methods but we need only 4.
POST– create a new resource
GET– get resource data
PUT– update a resource
DELETE– delete a resource
There is also
PATCH method which is very similar to
PUT should rewrite a whole resource and
PATCH only update
some attributes of a resource. More about
Simple example (we always work with objects)
REST greatly improves a simplicity of using the API. Let’s have a look at an example how we manage trainings:
We can access that URLs via
HTTP methods. If we want
to create a new training then we call the first URL. If we want to read
training data, or update data, or delete a training then we use the second URL
:training with some integer). Actually, REST force you take
an advantage of
that’s good. As you can see, to make operations with trainings we need just two
URLs (I call them access points).
The philosophy of REST is to access objects. In the example
was the object. The reason is simple – we can make CRUD operations (read,
write, update, delete) only with objects.
Well, you can ask: “What if I need to tell a trainee X wants to join training Y?”. I solved the problem by creating another access point:
Now we are working with
attendance object. Allowed HTTP methods for this
access point are PUT and DELETE.
If a trainee with ID 541 wants to join training with ID 1050 we call
method. Later the trainee changes his mind and wants to leave the training, so
we call the same URL with
How to send data to server with cURL
I’ll illustrate using REST API with curl utility.
Let’s create a new training:
1 2 3 4 5
A simplified server response can look like this (in JSON):
1 2 3 4 5 6 7 8
Now we know training ID. Getting information about training:
We haven’t changed training data so a server response looks exactly like in above example.
I made a mistake! The training should ends at 13:30, let’s change it:
1 2 3 4
A simplified server response:
1 2 3 4 5 6 7 8
This deletes training:
An obligatory server response:
1 2 3
This article was also published on my school blog.