The purpose of this series is to promote FastAPI and promote the translation of FastAPI Chinese official files. At present, 98% of the Chinese official files have been translated. If you are interested in FastAPI, you can contribute to this great open source project, such as proofreading, translation, review, etc.
Open source projects can’t grow without people’s support. Of course, the easiest way is to click Star on Github.
If you like FastAPI, you can also forward and republish this article to let more people know that Python has such a simple and fast back-end support library.
FastAPI official address: fastapi.tiangolo.com/zh/
Here are a few PR that need Review, and I hope you can participate in it.
- Github.com/tiangolo/fa…
- Github.com/tiangolo/fa…
- Github.com/tiangolo/fa…
- Github.com/tiangolo/fa…
- Github.com/tiangolo/fa…
- Github.com/tiangolo/fa…
- Github.com/tiangolo/fa…
- Github.com/tiangolo/fa…
- Github.com/tiangolo/fa…
The following is the text.
This guide will walk you through most of FastAPI’s features step by step.
Each chapter of this guide is step-by-step but has its own topic, so you can read the required chapters directly to address specific API requirements.
This guide is also a reference manual for your immediate reference.
Run the code
All of the code in this tutorial can be copied directly (in fact, it is a tested Python file).
To run the example, simply copy the code to main.py and start Uvicorn with the following command:
$ uvicorn main:app --reload
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [28720]
INFO: Started server process [28722]
INFO: Waiting for application startup.
INFO: Application startup complete.
Copy the code
It is highly recommended that you edit and run this code locally.
It’s only when you enter code in the editor that you can really get a feel for the benefits of FastAPI, how much code you need to type in, type checking, auto-completion, and so on.
Install FastAPI
The first step is to install FastAPI.
To follow this tutorial, you need to have all the optional dependency support libraries installed:
$ pip install fastapi[all]
Copy the code
. The above command also installs the server -Uvicorn that runs the FastAPI application.
!!!!!!!!! I made note of it.
You can install each support library separately. If you want to deploy your application to a production environment, install FastAPI: PIP install FastAPI: PIP install uvicorn[standard] install other optional dependency support libraries as required.Copy the code
Advanced User Guide
After the user Guide, you can continue with the advanced User Guide.
Advanced User Guide Based on this guide, the core concepts are the same, but more features are introduced.
You are advised to read the user guide first.
Develop a complete FastAPI application after learning the user guide. You can then extend the application with the features in the Advanced User guide.
The first step
The simplest FastAPI file looks like this:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root() :
return {"message": "Hello World"}
Copy the code
Copy the code to main.py.
Running real-time server:
$ uvicorn main:app --reload
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [28720]
INFO: Started server process [28722]
INFO: Waiting for application startup.
INFO: Application startup complete.
Copy the code
!!!!!!!!! I made note of it.
The 'uvicorn main:app' command is described as follows: * 'main' : 'main.py' is Python ** module **; * 'app' : 'main.py' object created by 'app = FastAPI()'; * '--reload' : After code update, restart the server. Use only during development.Copy the code
The following information is displayed:
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
Copy the code
This is the URL that FastAPI applications provide services to natively.
To view the document
Open your browser and visit http://127.0.0.1:8000.
The JSON response is as follows:
{"message": "Hello World"}
Copy the code
The API documentation
Jump to http://127.0.0.1:8000/docs.
View the automatically generated (Swagger UI) API documentation:
Alternative API documentation
Jump to http://127.0.0.1:8000/redoc.
View the auto-generated (ReDoc) alternative document:
OpenAPI
FastAPI uses OpenAPI (the standard that defines apis) to convert all apis into schematic diagrams.
Sketch plan
Schematic diagram is the definition and description of things, not the code to achieve the function, just abstract description.
API overview
In this guide, OpenAPI is the specification that defines the API sketch diagram.
The sketch here includes API paths, path parameters, and so on.
The data overview
The term sketch also refers to the structure of data such as JSON.
In this guide, data diagrams refer to JSON attributes, data types, and so on.
OpenAPI and JSON Schema
OpenAPI is used to define API sketch diagrams. The diagram contains the definitions made by JSON Schema for data sent and received by the API. JSON Schema is the JSON data Schema standard.
To viewopenapi.json
If you are interested in the OpenAPI raw sketch, FastAPI automatically generates JSON (sketch) describing all the apis.
Direct view: http://127.0.0.1:8000/openapi.json.
The JSON file begins as follows:
{
"openapi": "3.0.2"."info": {
"title": "FastAPI"."version": "0.1.0 from"
},
"paths": {
"/items/": {
"get": {
"responses": {
"200": {
"description": "Successful Response"."content": {
"application/json": {...Copy the code
What is OpenAPI for
The OpenAPI sketch is used to drive the two API documents built into FastAPI.
There are plenty of openapi-based alternatives, and it’s easy to add other alternatives for FastAPI applications.
OpenAPI can also be used to automatically generate client code that communicates with the API. For example, front-end, mobile, Internet of Things applications.
Step by step summary
Step 1: ImportFastAPI
from fastapi import FastAPI
Copy the code
FastAPI is a Python class that provides all the functionality for an API.
!!!!!!!!! Note “Technical details”
'FastAPI' is a direct descendant of 'Starlette'. 'FastAPI' calls all the features of Starlette.Copy the code
Step 2: CreateFastAPI
The instance
app = FastAPI()
Copy the code
The app variable is a class instance of FastAPI.
This instance is the primary interaction object for creating all apis.
This app is the variable referenced by Uvicorn in the following command:
$ uvicorn main:app --reload
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
Copy the code
If you create an application with the following code:
my_awesome_api = FastAPI()
Copy the code
To save the code to main.py, call Uvicorn as follows:
$ uvicorn main:my_awesome_api --reload
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
Copy the code
Step 3: Create a path
The path
The path is the first backslash (/) of the URL and everything after it.
In the following URL:
https://example.com/items/foo
Copy the code
… Path is:
/items/foo
Copy the code
!!!!!!!!! Info “info”
The ** path ** is usually also called ** endpoint ** or ** route **.Copy the code
When developing apis, paths are the primary way to separate concerns from resources.
operation
Operations refer to HTTP methods.
The common methods are as follows:
POST
GET
PUT
DELETE
Rare methods are as follows:
OPTIONS
HEAD
PATCH
TRACE
The HTTP protocol supports using any (or more) of the above methods to communicate with paths.
When you develop aN API, you typically use specific HTTP methods to perform specific operations.
Common methods:
POST
Create dataGET
: Read dataPUT
: Update dataDELETE
: Delete data
OpenAPI calls HTTP methods operations.
We also call this operation.
definePath manipulation decorator
@app.get("/")
Copy the code
@app.get(“/”) tells FastAPI’s lower functions to handle access requests as follows:
- The request path is
/
- Use get
!!!!!!!!! Info “@decorator specification”
The @something syntax is Python ** decorator **. It's like a decorative cap on top of a function (presumably hence the term's name). The decorator receives the function below and uses it to perform some operations. In this case, the decorator tells **FastAPI** that the path ** corresponding to the function below ** is'/' and 'get' ** operation **. This is the path manipulation decorator.Copy the code
Other common operations are as follows:
@app.post()
@app.put()
@app.delete()
And rare operations:
@app.options()
@app.head()
@app.patch()
@app.trace()
!!!!!!!!! I don’t want to tip you.
Feel free to use any action (HTTP methods). **FastAPI** does not enforce any specific meaning to an operation. The instructions in this chapter are guidelines, not requirements. For example, when using GraphQL, you usually use only the 'POST' method for all operations.Copy the code
Step 4: DefinePath manipulation function
The path manipulation function consists of the following parts:
- The path:
/
- operation:
get
- function:A decoratorThe lower function (is located
@app.get("/")
Below)
async def root() :
Copy the code
The path manipulation functions are Python functions.
FastAPI calls this function every time it receives a request to access the URL**/** using the GET method.
The path-manipulation function in this case is async.
We can also omit async def and define pathhandling functions as normal functions:
def root() :
Copy the code
!!!!!!!!! I made note of it.
If you don't know the difference between normal and asynchronous functions, see asynchronous: *** Can't wait? *** section.Copy the code
Step 5: Return the content
return {"message": "Hello World"}
Copy the code
Path manipulation functions can return dictionaries, lists, and single values such as strings and integers.
You can also return a Pydantic model (described later).
There are also many objects and models (ORM, etc.) that can be automatically converted to JSON. You can try using your favorite object, which is probably already supported by FastAPI.
summary
- The import
FastAPI
- create
app
The instance - writePath manipulation decorator(e.g.,
@app.get("/")
) - writePath manipulation function(e.g.,
def root(): ...
) - Running the development server (e.g
uvicorn main:app --reload
)