Frontend and Backend
Let's start in order. What are frontend and backend? The site has two sides: front and inner, respectively. 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 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:
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 page 127.0.0.1 : 5000, you will see the inscription โHello, World!โ. From the server side, you will see the following message:
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 do A GET request to our server and we get into the index function - from here โHello, World!โ Is taken. 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 stands for REpresentational State Transfer (or, in a simpler way, 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 necessarily!) 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:
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 them. 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:
data = {
1: {
"login": "login1",
"password": "Qwerty1"},
2: {
"login": "login2",
"password": "Ytrewq2"}
}
We have a data in which there are two users so far (login1 and login2) and we will CRUD this date. It should be said 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 (return 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:
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 return'ah). 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 availability 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.