#?
Getting Started
Install fastapi and ASGI server (e.g. uvicorn):
Make sure you are using Python 3.6.7 If
pip and
python give you a python 2 version, you may have to use
pip3
python3
. Also, check out my article on getting started with python.pip?install?fastapi?uvicorn

file:
from?fastapi?import?FastAPI app?=?FastAPI() @app.get("/") def?home(): ????return?{"Hello":?"World"}Run development
then To run for development, you can run
uvicorn main:app --reload
That’s all a simple server does! Now you can check //localhost:8000/ to see the "Home Page". And, as you can see, the JSON response "just works"! You can also get Swagger UI for free at //localhost:8000/docs.
As mentioned before, it is easy to validate the data (and generate Swagger documentation for the accepted data formats). Just add the
import from fastapi and use it to force validation: <pre class="brush:php;toolbar:false">from?fastapi?import?FastAPI,?Query
@app.get('/user')
async?def?user(
????*,
????user_id:?int?=?Query(...,?title="The?ID?of?the?user?to?get",?gt=0)
):
??return?{?'user_id':?user_id?}</pre>
The first parameter ...
is the default value if the user does not provide a value This default value is provided. If set to None
, there is no default value and the parameter is optional. In order that there is no default value and the parameter is mandatory, use Ellipsis, or
instead. If you run this code, you will automatically see the update on the swagger UI:
The Swagger UI allows you to view the new /user route and use a specific Make the request with your user IDIf you enter any user ID, you will see that it will automatically perform the request for you, for example //localhost:8000/user?user_id=1. In the page you can only see the user ID echoed! If you want to use the path parameter instead (so that it is/user/1, then just enter and use Path
instead ofQuery. It is also possible to combine both
Post routes
POST route, you can just define the input
@app.post('/user/update') async?def?update_user( ????*, ????user_id:?int, ????really_update:?int?=?Query(...) ): ????pass
in this case, you can see that
user_id is only defined as an integer without
Query or
Path; which means it will be in the POST request body. If You accept more complex data structures, such as JSON data, you should look into request models.
Request and Response Models You can use Pydantic models to record and declare detailed Request and response models. Not only does this allow you to have automatic OpenAPI documentation for all your models, but it also validates the request and response models to ensure that any POST data entered is correct and that the data returned conforms to the model.
from?pydantic?import?BaseModel class?User(BaseModel): ????id::?int ????name:?str ????email:?strThen if you want to take the user model as input you can do this:
async?def?update_user(*,?user:?User):
????pass
Or if you want to Used as output: @app.get('/user')
async?def?user(
????*,
????user_id:?int?=?Query(...,?title="The?ID?of?the?user?to?get",?gt=0),
????response_model=User
):
??my_user?=?get_user(user_id)
??return?my_user
Routing and decomposing a larger API
from?fastapi?import?APIRouter from?.user?import?router?as?user_router router?=?APIRouter() router.include_router( ????user_router, ????prefix='/user', ????tags=['users'], )###Then you can find this in ###app/routers/v1/user.py## # using the user code above - just import ###APIRouter### and use ###@ router.get('/')< aaaa>### instead of ###@ app.get(' /user')###. It will automatically route to ###/user /### because the route is prefix relative. ###
from?fastapi?import?APIRouter router?=?APIRouter() @router.get('/') async?def?user( ????*, ????user_id:?int?=?Query(...,?title="The?ID?of?the?user?to?get",?gt=0), ????response_model=User ): ??my_user?=?get_user(user_id) ??return?my_user###Finally, use all ## in your application #v1###router, just edit ###main.py### to: ###
from?fastapi?import?FastAPI from?app.routers?import?v1 app?=?FastAPI() app.include_router( ????v1.router, ????prefix="/api/v1" )### You can chain routers at will this way, allowing you to split large applications and have versions ized API. #########Dockerizing and Deploying#########One of the authors of Fastapi makes Dockerizing surprisingly easy! The default ###Dockerfile### is 2 OK!###
FROM?tiangolo/uvicorn-gunicorn-fastapi:python3.7 COPY?./app?/app
是否想通過自動(dòng)重新加載進(jìn)行 Dockerize 開發(fā)?這是我在撰寫文件中使用的秘方:
version:?"3" services: ??test-api: ????build:?.. ????entrypoint:?'/start-reload.sh' ????ports: ????????-?8080:80 ????volumes: ????????-?./:/app
這會(huì)將當(dāng)前目錄掛載為app
并將在任何更改時(shí)自動(dòng)重新加載。您可能還想將app / app
用于更大的應(yīng)用程序。
有用的網(wǎng)址
所有這些信息都來自 Fastapi網(wǎng)站,該文檔具有出色的文檔,我鼓勵(lì)您閱讀。此外,作者在 Gitter 上非?;钴S并樂于助人!
結(jié)論
就是這樣-我希望本指南對(duì)您有所幫助,并且您會(huì)像我一樣喜歡使用 Fastapi。
推薦教程:Python教程
The above is the detailed content of Python quick use of REST API. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The key to dealing with API authentication is to understand and use the authentication method correctly. 1. APIKey is the simplest authentication method, usually placed in the request header or URL parameters; 2. BasicAuth uses username and password for Base64 encoding transmission, which is suitable for internal systems; 3. OAuth2 needs to obtain the token first through client_id and client_secret, and then bring the BearerToken in the request header; 4. In order to deal with the token expiration, the token management class can be encapsulated and automatically refreshed the token; in short, selecting the appropriate method according to the document and safely storing the key information is the key.

To test the API, you need to use Python's Requests library. The steps are to install the library, send requests, verify responses, set timeouts and retry. First, install the library through pipinstallrequests; then use requests.get() or requests.post() and other methods to send GET or POST requests; then check response.status_code and response.json() to ensure that the return result is in compliance with expectations; finally, add timeout parameters to set the timeout time, and combine the retrying library to achieve automatic retry to enhance stability.

In Python, variables defined inside a function are local variables and are only valid within the function; externally defined are global variables that can be read anywhere. 1. Local variables are destroyed as the function is executed; 2. The function can access global variables but cannot be modified directly, so the global keyword is required; 3. If you want to modify outer function variables in nested functions, you need to use the nonlocal keyword; 4. Variables with the same name do not affect each other in different scopes; 5. Global must be declared when modifying global variables, otherwise UnboundLocalError error will be raised. Understanding these rules helps avoid bugs and write more reliable functions.

To create modern and efficient APIs using Python, FastAPI is recommended; it is based on standard Python type prompts and can automatically generate documents, with excellent performance. After installing FastAPI and ASGI server uvicorn, you can write interface code. By defining routes, writing processing functions, and returning data, APIs can be quickly built. FastAPI supports a variety of HTTP methods and provides automatically generated SwaggerUI and ReDoc documentation systems. URL parameters can be captured through path definition, while query parameters can be implemented by setting default values ??for function parameters. The rational use of Pydantic models can help improve development efficiency and accuracy.

Add timeout control to Python's for loop. 1. You can record the start time with the time module, and judge whether it is timed out in each iteration and use break to jump out of the loop; 2. For polling class tasks, you can use the while loop to match time judgment, and add sleep to avoid CPU fullness; 3. Advanced methods can consider threading or signal to achieve more precise control, but the complexity is high, and it is not recommended for beginners to choose; summary key points: manual time judgment is the basic solution, while is more suitable for time-limited waiting class tasks, sleep is indispensable, and advanced methods are suitable for specific scenarios.

How to efficiently handle large JSON files in Python? 1. Use the ijson library to stream and avoid memory overflow through item-by-item parsing; 2. If it is in JSONLines format, you can read it line by line and process it with json.loads(); 3. Or split the large file into small pieces and then process it separately. These methods effectively solve the memory limitation problem and are suitable for different scenarios.

In Python, the method of traversing tuples with for loops includes directly iterating over elements, getting indexes and elements at the same time, and processing nested tuples. 1. Use the for loop directly to access each element in sequence without managing the index; 2. Use enumerate() to get the index and value at the same time. The default index is 0, and the start parameter can also be specified; 3. Nested tuples can be unpacked in the loop, but it is necessary to ensure that the subtuple structure is consistent, otherwise an unpacking error will be raised; in addition, the tuple is immutable and the content cannot be modified in the loop. Unwanted values can be ignored by \_. It is recommended to check whether the tuple is empty before traversing to avoid errors.

Python default parameters are evaluated and fixed values ??when the function is defined, which can cause unexpected problems. Using variable objects such as lists as default parameters will retain modifications, and it is recommended to use None instead; the default parameter scope is the environment variable when defined, and subsequent variable changes will not affect their value; avoid relying on default parameters to save state, and class encapsulation state should be used to ensure function consistency.
