(Introduction) FastAPI for the Python web Framework - an API with higher performance than Flask and Tornada

Officially, the FastAPI is a modern, fast (high-performance) Web framework that uses Python 3.6+ to build APIs based on standard Python type tips



FastAPI on the shoulders of giants?

To a large extent, this giant is the Flask framework.


The FastAPI is syntactically very similar to Flask and has the same workmanship.

Technical background: Py3.6+, Starlette, Pydantic

Not only is the FastAPI, but Sanic is also a framework for Flask-based Web API s.


Say nothing, the code always gives people a pleasant (cuddle) feeling and opens up straight.


install

pip install fastapi 
pip install uvicorn



Create a main.py file


from fastapi import FastAPI

app = FastAPI() # Establish api object

@app.get("/") #Root Route
def root():
    return {"Wuhan""Come on."}

@app.get("/say/{data}")
def say(data: str,q: int):
    return {"data": data, "item": q}


The simplest FastAPI app is built on top, which looks exactly like Flask and has an unknown joy.


Use the following command to start the server:


uvicorn main:app --reload


FastAPI recommends using uvicorn to run services, Uvicorn is a lightning fast ASGI server built on uvloop and httptools.


uvicorn main:app means:

Main: file main.py

app: Created Enabled Object

reload: Hot start, easy code development


The startup interface is as follows:

        


INFO info tells us that we've listened on the local port 8000 and that we've visited http://127.0.0.1:8000 for results


Incoming parameters



Take a look at the asynchronous code for the FastAPI


from fastapi import FastAPI

app = FastAPI() # Establish api object

@app.get("/") #Root Route
async def root():
    return {"Wuhan""Come on."}

@app.get("/say/{data}")
async def say(data: str,q: int = None):
    return {"data": data, "q": q}


Access results are the same when the service is turned on.


In the routing method above, we passed in a q parameter and it was initially None. If no default value is given and no parameter is passed, the code will directly error.

Let's see how the FastAPI handles errors:

        

You can see that even errors are graceful input of a JSON with an error field, which is very friendly, which also reflects the FastAPI's ability to reduce more human errors and return more simply and intuitively.


On the command line:

        


Check out the interactive documentation for the FastAPI

According to the official document, open http://127.0.0.1:8000/docs


See:

        


Supports dynamic incoming data:

        

        

Result:


It is also incredibly friendly from an interactive experience, making code more robust in production.


Now we've experienced a fast wave of FastAPI Sausage operations, code-wise similar to Flask and better.


Then take a look at the performance response ranking of the latest Python web Framework


Flask is completely crushed in terms of concurrency (and actually leads tornado, which is also an asynchronous framework), so it seems that the FastAPI is not really a cover-up, it's really a high-performance API framework!


Query parameters


Let's start with the official little demo

from fastapi import FastAPI

app = FastAPI()

fake_items_db = [{"item_name""Foo"}, {"item_name""Bar"}, {"item_name""Baz"}]


@app.get("/items/")
async def read_item(skip: int = 0, limit: int = 10):
    return fake_items_db[skip : skip + limit]



The query is a set of key-value pairs in the URL that follow the keyword, separated by &characters.


Query in url

http://127.0.0.1:8000/items/?skip=0&limit=10


skip: the start parameter of the query

limit: end parameter of query


Query list returned successfully.


Query Parameter Type Conversion

The FastAPI is smart enough to distinguish between path parameters and query parameters.


Take a look at a specific example:

from fastapi import FastAPI

app = FastAPI()

@app.get("/items/{item_id}")
async def read_item(item_id: str, q: str = 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



Look at its access path and perform any of the following url access methods


http://127.0.0.1:8000/items/Wuhan Petroleum? short=1


http://127.0.0.1:8000/items/Wuhan Petrol? short=True


http://127.0.0.1:8000/items/Wuhan Petroleum? short=true


http://127.0.0.1:8000/items/Wuhan Petroleum? short=on


http://127.0.0.1:8000/items/Wuhan Petroleum? short=yes



You can see that any uppercase or lowercase letter, for example, is converted to the bool value parameter True, which is called the fuzzy validation parameter, which is good news for developers.


What you need to know is that if the short parameter does not have a default value, it must be passed, otherwise the FastAPI will return error information similar to the following.


{
    "detail": [
        {
            "loc": [
                "query",
                "needy"
            ],
            "msg""field required",
            "type""value_error.missing"
        }
    ]
}



Create Data Model

As mentioned earlier, the FastAPI relies on the Pydantic module, so first you need to import the BaseModel class of Pydantic.


from fastapi import FastAPI
from pydantic import BaseModel

# Request Body Class
class Item(BaseModel):
    name: str = "Go to Wuhan!!"
    description: str = None
    price: float = 233
    tax: float = None


app = FastAPI()


@app.post("/items/")
async def create_item(item: Item):
    return item


Send a post request to submit an Item and return to see the submission process.



Successfully submitted and returned 200 status code

Request Body+Path+Query Parameter, adding url dynamic path parameter and query parameter based on request body

from fastapi import FastAPI
from pydantic import BaseModel


class Item(BaseModel):
    name: str
    description: str = None
    price: float
    tax: float = None


app = FastAPI()


@app.put("/items/{item_id}")
async def create_item(item_id: int, item: Item, q: str = None):
    result = {"item_id": item_id, **item.dict()}
    if q:
        result.update({"q": q})
    return result


The put method is used for updating and returns a dictionary successfully after passing in the parameter.


About Template Engine


The FastAPI does not have the same built-in template engine (Jinja2) as Flask, which means there is no default template engine. On the other hand, the FastAPI is more flexible and comfortable in choosing a template engine.


Take the Jinja2 template as an example


Installation Dependency

pip install jinja2
pip install aiofiles # Asynchronous static file for fastapi


concrete use

# -*- coding:utf-8 -*-
from fastapi import FastAPI, Request
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
import uvicorn

app = FastAPI()

app.mount("/static", StaticFiles(directory="static"), name="static"# Mount static files, specify directory


templates = Jinja2Templates(directory="templates"#Template Directory


@app.get("/data/{data}")
async def read_data(request: Request, data: str):
    return templates.TemplateResponse("index.html", {"request": request, "data": data})

if __name__ == '__main__':
    uvicorn.run(app, host="127.0.0.1", port=8000)


html file rendering

<html>
<head>
    <title>Wuhan Petroleum</title>
</head>
<body>
    <h1>Shout: {{ data }}</h1>
</body>
</html>



Type http://127.0.0.1:8000/data/Wuhan Gas in the browser



It is worth noting that when the TemplateRespone response is returned, the context object of the request must be brought with the incoming parameters placed in the same dictionary.


This way, you can use the familiar Jinja2 just like Flask, haha.



To summarize, FastAPI is also simple in use, faster, better in performance, higher in fault tolerance and better overall.But I'm imagining a framework that's going to be published so fast. After all, it doesn't take long to publish, and there's no third-party libraries and plug-ins like the Flask framework, so it will take some time to actually replace it. Be calm and cool.



Okay, that's almost the end of some basic uses of the FastAPI. The official documentation for the FastAPI has detailed descriptions and examples, and the introductory chapter ends here.


Official documents: https://fastapi.tiangolo.com/

Reference website: http://pdcfighting.com/


Keywords: Python pip JSON

Added by Bleej on Thu, 16 Apr 2020 21:26:17 +0300