There is a very simple requirement: write an HTTP interface that sends a JSON string using POST mode. The interface reads the sent parameters, processes one of the parameters, and returns it.
If we were to use Flask to develop this interface, the code would look like this:
from flask import Flask, request
app = Flask(__name__)
@app.route('/insert', methods=['POST'])
def insert(a):
info = request.json
name = info['name']
age = info['age']
age_after_10_years = age + 10
msg = F 'The man's name is:{name}10 years later, this person's age:{age_after_10_years}'
return {'success': True.'msg': msg}
Copy the code
The code already looks pretty neat. Let’s send a request in requests to see what happens, as shown in the figure below:
It seems to be all right.
Now, I’m going to break things a little bit, change the age field to a string, and run it again:
As expected, an error was reported.
Now we change the age field back to a number, but remove the name field directly:
Another error.
In order to prevent users from submitting data according to the rules, we must do a good job in the interface of abnormal data judgment. This makes the code more complicated after adding the judgment:
@app.route('/insert', methods=['POST'])
def insert(a):
info = request.json
name = info.get('name'.' ')
if not name:
return {'success': False.'msg': 'Name parameter cannot be omitted, cannot be empty! '}
age = info.get('age'.0)
if not isinstance(age, int):
return {'success': False.'msg': The 'age argument is not a number! '}
age_after_10_years = age + 10
msg = F 'The man's name is:{name}10 years later, this person's age:{age_after_10_years}'
return {'success': True.'msg': msg}
Copy the code
Flask, it seems, allows you to write a working project in very short code. But to write a working project, you still need to write more code yourself.
Let’s take a look at how simple this project can be with modern Web frameworks: FaskApi:
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class People(BaseModel):
name: str
age: int
address: str
salary: float
@app.post('/insert')
def insert(people: People):
age_after_10_years = people.age + 10
msg = F 'The man's name is:{people.name}10 years later this person's age:{age_after_10_years}'
return {'success': True.'msg': msg}
Copy the code
We’re still using requests to send a message to the HTTP interface developed by the FastApi. For normal data, normal use:
Now let’s change the age field to a string:
Return a friendly message telling me that the type is incorrect: the age field is not an INTEGER.
Let’s try removing the name field again:
A friendly message is displayed indicating that the name field is missing.
Throughout the process, the type checking is done by the FastApi itself. We save a lot of time.
I’ve been using Flask for four years, but after 5 minutes of using the FastApi, I’ve decided not to use Flask in the future.
Back up, let’s take a look at the FastApi.
Install FastApi using PIP or Pipenv:
pip install fastapi
pipenv install fastapi
Copy the code
Once the installation is complete, let’s complete the first API:
from fastapi import FastAPI
app = FastAPI()
@app.get('/')
def index(a):
return {'message': 'You have created the FastApi service correctly! '}
Copy the code
It’s written almost the same way as Flask. In Flask, however, we define routes with the decorator @app.route(‘/’). And here I’m going to say @app.get(‘/’)
As shown in the figure below:
With the code written, we need to use Uvicorn to run the FastApi. First install uvicorn using PIP or Pipenv:
pip install uvicorn
pipenv install uvicorn
Copy the code
Then execute the command:
uvicorn main:app --reload
Copy the code
Where main means our code file is main.py, and app means the name of the FastApi object we initialized. The –reload parameter means that the change takes effect immediately and no restart is required.
After running this command, we can visit http://127.0.0.1:8000 and see that the interface has returned JSON data correctly:
So how do you define a GET method with arguments? Let’s write another piece of code:
@app.get('/query/{uid}')
def query(uid):
msg = F 'your query uid is:{uid}'
return {'success': True.'msg': msg}
Copy the code
After writing the code, we can directly access the new address in the browser and see that the change has taken effect, as shown below:
What if you want to limit uid to a number, not a string? You only need to add 4 characters:
@app.get('/query/{uid}')
def query(uid: int):
msg = F 'your query uid is:{uid}'
return {'success': True.'msg': msg}
Copy the code
Use the type annotation for the parameters of the query function, which is of type int. Now let’s access the interface again:
An error occurs when the argument after query is not an integer.
Let’s take a look at the POST method we started with in this article. In Flask, we need to manually verify the format of the data posted by the user and whether the fields are correct.
But with FastApi, we just need type annotations to solve all the problems. From pydantic import BaseModel; from pydantic import BaseModel; from pydantic import BaseModel; from pydantic import BaseModel;
from pydantic import BaseModel
app = FastAPI()
class People(BaseModel):
name: str
age: int
address: str
salary: float
Copy the code
The People class specifies its four fields and their types through the type annotation. Now let’s implement the POST method:
@app.post('/insert')
def insert(people: People):
age_after_10_years = people.age + 10
msg = F 'The man's name is:{people.name}10 years later this person's age:{age_after_10_years}'
return {'success': True.'msg': msg}
Copy the code
The insert parameter people is specified by the type annotation as people.
When we POST data, the FastApi automatically checks the data against the fields defined in People and returns an error message.
In addition to making it easy to develop interfaces, FastApi automatically generates interface documentation for you. You visit http://127.0.0.1:8000/docs, you can see the interface document has been generated automatically better:
This interface can not only look at, but also directly modify the sample data on the interface page, send requests, and field tests:
This is a very brief introduction to the FastApi. Those who are interested can consult its official documentation
Finally, FastApi is an asynchronous Web framework that is very, very, very fast. Far more than Flask.
FastApi is one of the fastest Web frameworks out there. The speed can match golang-written interface. One of the fastest Python frameworks available