I Want To Skip the Flask to Come to Fastapi

There is a very simple requirement: write an HTTP interface and send a JSON string using POST. The interface reads the parameters sent, processes one of the parameters, and returns it.
If we develop this interface using Flask, the code looks like this:

from flask import Flask, request

app = Flask(__name__)


@app.route('/insert', methods=['POST'])
def insert():
    info = request.json
    name = info['name']
    age = info['age']
    age_after_10_years = age + 10
    msg = f'此人名叫:{name},10年后,此人年龄:{age_after_10_years}'
    return {'success': True, 'msg': msg}

The code already looks terse. We use equests a request to see the effect, as shown below:
This is image title

Looks fine.

Now, let me break it up, change the age field to a string, and run it again:
This is image title

Unsurprisingly, the error was reported.

Now we change the age fields back to numbers, but remove the `name fields directly:
This is image title

Wrong again.
In order to prevent users from submitting data in accordance with the rules, we must make judgments on various abnormal data in the interface. So the code after adding the judgment becomes complicated:

@app.route('/insert', methods=['POST'])
def insert():
    info = request.json
    name = info.get('name', '')
    if not name:
        return {'success': False, 'msg': 'name 参数不可省略,不可为空!'}
    age = info.get('age', 0)
    if not isinstance(age, int):
        return {'success': False, 'msg': 'age参数不是数字!'}
    age_after_10_years = age + 10
    msg = f'此人名叫:{name},10年后,此人年龄:{age_after_10_years}'
    return {'success': True, 'msg': msg}

It seems that using Flask allows you to write a working project with very short code. But to write a working project, you still need to write more code yourself.
Let’s take a look at a modern web framework: FaskApito what extent can this project be simplified:

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'此人名字叫做:{people.name},十年后此人年龄:{age_after_10_years}'
    return {'success': True, 'msg': msg}

We still use requests to send a message to the HTTP interface developed by FastApi. For normal data, use normally:
This is image title

Now we change the age fields to strings:
This is image title

Back to friendly tips and tell me 类型错误:age 字段不是 integer.

Let’s try again and name remove the fields:
This is image title

Return friendly information, tips 值错误:name字段丢失.

Throughout the process, the type checking is done by FastApi itself. We save a lot of time.

I have used Flask for four years, but after using FastApi for 5 minutes, I decided not to use Flask in the future.

Looking back, let’s introduce FastApi.

Use pip or pipen vinstall FastApi:

pip install fastapi
pipenv install fastapi

After the installation is complete, let’s complete the first API:

from fastapi import FastAPI

app = FastAPI()


@app.get('/')
def index():
    return {'message': '你已经正确创建 FastApi 服务!'}

The writing here is almost the same as Flask. It’s just that in Flask, we define the decorator for routes as @app.route('/'). And here is written @app.get('/')

As shown below:
This is image title

After writing the code, we need to use it uvicorn to run FastApi. First use pip or pipenv install uvicorn:

pip install uvicorn
pipenv install uvicorn

Then execute the command:

uvicorn main:app --reload

Which main represents our code file main.py, app indicate the name of FastApi we initialize the object. --reload The parameter indicates that it will take effect immediately after the code is modified, and no restart is required.

After running the command, we http://127.0.0.1:8000 can see that the interface has correctly returned data in JSON format:
This is image title

So how to define a GET method with parameters? We write another piece of code:

@app.get('/query/{uid}')
def query(uid):
    msg = f'你查询的 uid 为:{uid}'
    return {'success': True, 'msg': msg}

After writing the code, we visit the new address directly in the browser, and we can see that the modification has taken effect, as shown in the following figure:
This is image title

What if you want to restrict the uid to only numbers, not strings? You just need to add 4 more 字符:

@app.get('/query/{uid}')
def query(uid: int):
    msg = f'你查询的 uid 为:{uid}'
    return {'success': True, 'msg': msg}

query Use type annotations for the parameters of the function , as int. Now let’s access the interface again:
This is image title

When the parameter after query is not an integer, an error is reported normally.

Let’s take a look at the POST method at the beginning of this article. When using Flask, we need to manually verify the format of the data submitted by the user’s POST, and the fields are correct.

But when using FastApi, we only need type annotation to solve all problems. First we import from pydantic import BaseModel, then inherit BaseModel the data fields and format that we allow to be submitted by the POST method:

from pydantic import BaseModel

app = FastAPI()


class People(BaseModel):
    name: str
    age: int
    address: str
    salary: float

People This class is type-annotated, specifying the 4 fields in it and their types. Now let’s implement the POST method:

@app.post('/insert')
def insert(people: People):
    age_after_10_years = people.age + 10
    msg = f'此人名字叫做:{people.name},十年后此人年龄:{age_after_10_years}'
    return {'success': True, 'msg': msg}

insert The parameters of the function are people specified as People types by type annotation.

When we use the POST method to submit data, FastApi will automatically People verify the data based on the fields defined in it, and return an error message if it is found to be incorrect.

In addition to making it easy to develop interfaces, FastApi also automatically generates interface documentation for us. Everyone visits http://127.0.0.1:8000/docs, you can see that the interface document has been automatically generated:
This is image title

This interface can not only see, but also directly modify sample data, send requests, and test on the interface page:
This is image title

The above is a minimal introduction to FastApi.

#fastapi #flask

I Want To Skip the Flask to Come to Fastapi
35.45 GEEK