What is REST API
REST API is needed to create a website. But after all, this requires a lot of things (you will say) – so in which part do we need REST API?
Frontend and Backend
Let’s start step-by-step. What are frontend and backend?
The site has two sides: front and inner. The first is usually responsible for the visual arrangement of objects on the page (where are which pictures, where is what text and where are which buttons).
The second is responsible for “actions”. Usually these are clicks on the same buttons or on other “things” on the site. For example, you go to the page of your favorite social network and first you need to log into your account. On the front side (frontend) you enter your username and password and click the “Login” button.
At this time, the request is sent to the database to check the existence of such a user, and if it is successful, you will be taken to the social network under your account, otherwise, you will see an error message. In this case, the backend is essentially responsible for sending a request to the database. It is usually divided into three sub-parts:
- Web API for accepting requests
- Business logic for processing requests
- Interaction with the database
In this article, we will talk mainly about API or Application Programming Interface and a little about business logic. But first, let’s create a server.
Creating your own server
This is how the simplest python server application looks like using the flask framework:
1 2 3 4 5 6 7 8 9 10 11 |
from flask import Flask app = Flask(__name__) @app.route("/") def index(): return "Hello, World!" app.run() |
There is already one empty route (“/”) and if you run this application and open the browser on the page 127.0.0.1:5000, you will see the inscription “Hello, World!”. From the server side, you will see a message like this:
127.0.0.1 – – [07 / Aug / 2020 20:32:16] “GET / HTTP / 1.1” 200 –
Thus, by going to this link in the browser (client), we make a GET request to our server and get into the index function – this is where “Hello, World!” comes from. You can add other queries (much more complex) along other routes (or not necessarily). As I said, in this case, we used a GET request – the standard default. But there are many others, the most popular of which are POST, PUT, DELETE. But why is this necessary?
Create Read Update Delete
First, REST means REpresentational State Transfer. In fact, the definition of REST itself is not that important, but it is usually associated with another acronym – CRUD – Create Read Update Delete. At the very beginning, I gave an example related to a database and these four operations are an integral part of working with it (well, or just with data).
Second, a REST or RESTfull API must support handling these four actions. This is where the GET, POST, PUT, DELETE methods come in handy. As a rule (not necessary!) The POST method is used to add new data (Create), GET – to read (Read), PUT – to update existing data (Update) and DELETE, respectively, to delete (Delete). For example, the same flask application can be redesigned like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
from flask import Flask, request app = Flask(__name__) @app.route("/", methods=["POST", "GET", "PUT", "DELETE"]) def index(): if request.method == "POST": if request.method == "GET": if request.method == "PUT": if request.method == "DELETE": app.run() |
This is the primitive REST API. The frontend side can now send requests and, depending on their type, we will take further actions.
Working with data
Our current application is not interesting at all – it would be nice to work with some data. To do this, you need to think about how to transfer it. The most popular way is JSON format (but you can use others, for example, XML). It is analogous to a dictionary in python and is very easy to use. I will use primitive data for an example with authorization on a social network:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
data = { 1: { "login": "login1", "password": "Qwerty1"}, 2: { "login": "login2", "password": "Ytrewq2"} |
We have data, in which there are two users so far (login1 and login2) and we will CRUD this data. It is worth saying that all four methods rarely work on the same route and usually do this: for the GET methods (return all users) and POST the route is used, for example, “/ users”, and for the GET methods (give out one user by its id), PUT and DELETE “/ users / id”. It should also be noted that to update and create new users, we receive data about them in the request body (request.json). Now our program can be rewritten as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
from flask import Flask, request app = Flask(__name__) data = { 1: { "login": "login1", "password": "Qwerty1"}, 2: { "login": "login2", "password": "Ytrewq2"} } @app.route("/users", methods=["POST", "GET"]) def work_with_users(): if request.method == "POST": data[max(data.keys())+1] = request.json return {"message": "User was created"}, 201 if request.method == "GET": return data, 200 @app.route("/users/<int:user_id>", methods=["GET", "PUT", "DELETE"]) def work_with_user_by_id(user_id): if request.method == "GET": return data[user_id], 200 if request.method == "PUT": data[user_id]["login"] = request.json["login"] data[user_id]["password"] = request.json["password"] return {"message": "User was updated"}, 200 if request.method == "DELETE": data.pop(user_id) return {"message": "User was deleted"}, 200 app.run() |
There are many programs for testing requests (Postman, Fiddler, Insomnia …) and I recommend that you familiarize yourself with one of them (personally, Postman is my favorite). With their help, you can see what comes as a result of the request and with what status code (numbers 200/201 in returns). And you can also stage sending data by adding it to the request body.
It is also worth noting that this approach is not currently used, and the flask-restplus library (or flask-restx, which replaced it) is usually used, but I think that first you need to get acquainted with pure flask. It is also necessary to check the presence of data and their correctness and provide for the return of an error in the opposite cases.
Conclusion
REST APIs are simply CRUD methods that are accessed by the client side of the site along specific routes. By ear and glance, this may be difficult to perceive, so I recommend writing your own server by analogy with the example. Personally, I find flask one of the easiest frameworks for this, and if you are a beginner, then I advise you to try it.
Related Posts
Leave a Reply Cancel reply
Service
Categories
- DEVELOPMENT (102)
- DEVOPS (53)
- FRAMEWORKS (25)
- IT (24)
- QA (14)
- SECURITY (13)
- SOFTWARE (13)
- UI/UX (6)
- Uncategorized (8)