Construction and testing of FastApi

1. Installation of fastapi

1-1. Use pip to install

Statement to install fastapi

pip install fastapi -i https://mirrors.aliyun.com/pypi/simple

Because fastapi startup depends on uvicorn, we also need to install uvicorn.

pip install uvicorn -i https://mirrors.aliyun.com/pypi/simple

Let's verify that the installation was successful.

verify

We create a file called main.py.

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def root():
    return {
    
    "message": "Hello World"}

Then we execute a command:

uvicorn main:app --reload
uvicorn main:app 命令含义如下:

main:main.py 文件(一个 Python「模块」)。
app:在 main.py 文件中通过 app = FastAPI() 创建的对象。
--reload:让服务器在更新代码后重新启动。仅在开发时使用该选项。
如果服务器返回了一串结果是:
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [8438] using statreload
INFO:     Started server process [8440]
INFO:     Waiting for application startup.
INFO:     Application startup complete.

Open a browser and visit http://127.0.0.1:8000.
You will see a JSON response like this:

{
    
    "message": "Hello World"}

Interactive API Documentation

Jump to http://127.0.0.1:8000/docs.

You will see automatically generated interactive API documentation.
insert image description here

optional parameters

In the same way, you can declare optional query parameters by setting their default value to None:

from typing import Union

from fastapi import FastAPI

app = FastAPI()


@app.get("/items/{item_id}")
async def read_item(item_id: str, q: Union[str, None] = None):
    if q:
        return {
    
    "item_id": item_id, "q": q}
    return {
    
    "item_id": item_id}

In this example, the function parameter q will be optional and default to None.

Query parameter type conversion

You can also declare bool types and they will be converted automatically:

from typing import Union

from fastapi import FastAPI

app = FastAPI()


@app.get("/items/{item_id}")
async def read_item(item_id: str, q: Union[str, None] = None, short: bool = False):
    item = {
    
    "item_id": item_id}
    if q:
        item.update({
    
    "q": q})
    if not short:
        item.update(
            {
    
    "description": "This is an amazing item that has a long description"}
        )
    return item

In this example, if you visit:

http://127.0.0.1:8000/items/foo?short=1

or

http://127.0.0.1:8000/items/foo?short=True

or

http://127.0.0.1:8000/items/foo?short=true

or

http://127.0.0.1:8000/items/foo?short=on

or

http://127.0.0.1:8000/items/foo?short=yes

or any other variant (uppercase, capitalized, etc.), your function will receive the boolean value True for the short parameter. The same is true for the value of False.

additional checksum

We intend to add the constraint that even though q is optional, as long as it is provided, the parameter value cannot exceed 50 characters in length.

Import Query

To do this, first import Query from fastapi:

from typing import Union

from fastapi import FastAPI, Query

app = FastAPI()


@app.get("/items/")
async def read_items(q: Union[str, None] = Query(default=None, max_length=50)):
    results = {
    
    "items": [{
    
    "item_id": "Foo"}, {
    
    "item_id": "Bar"}]}
    if q:
        results.update({
    
    "q": q})
    return results

Guess you like

Origin blog.csdn.net/weixin_50153843/article/details/129396620