国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
If you run this code, you will automatically see the update on the swagger UI: " > instead. If you run this code, you will automatically see the update on the swagger UI:
, then just enter and use Path" >/user/1, then just enter and use Path
有用的網(wǎng)址" >有用的網(wǎng)址
結(jié)論
Home Backend Development Python Tutorial Python quick use of REST API

Python quick use of REST API

Jun 15, 2020 pm 06:15 PM
python

Python quick use of REST API

#?

Fastapi is a python-based framework that encourages the use of Pydantic and OpenAPI (formerly Swagger) for documentation, Docker for rapid development and deployment, and simple testing based on the Starlette framework.

It provides many benefits such as automatic OpenAPI validation and documentation without adding unnecessary bloat. I think there's a good balance between not providing any built-in functionality and providing too much built-in functionality.

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

and

python3

. Also, check out my article on getting started with python.

pip?install?fastapi?uvicorn
and add the old "hello world" in the main.py

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.

Validation

As mentioned before, it is easy to validate the data (and generate Swagger documentation for the accepted data formats). Just add the

Query

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=&quot;The?ID?of?the?user?to?get&quot;,?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 ID

If 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 of

Query. It is also possible to combine both Post routes

If you have a

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.

Just declare the model like this:

from?pydantic?import?BaseModel

class?User(BaseModel):
????id::?int
????name:?str
????email:?str
Then 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

You can use ###APIRouter### to decompose the api into routes. For example, I have Found this in my API ###app/routers/v1/__init__.py######
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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to handle API authentication in Python How to handle API authentication in Python Jul 13, 2025 am 02:22 AM

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.

How to test an API with Python How to test an API with Python Jul 12, 2025 am 02:47 AM

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.

Python variable scope in functions Python variable scope in functions Jul 12, 2025 am 02:49 AM

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.

Python FastAPI tutorial Python FastAPI tutorial Jul 12, 2025 am 02:42 AM

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.

Python for loop with timeout Python for loop with timeout Jul 12, 2025 am 02:17 AM

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 parse large JSON files in Python? How to parse large JSON files in Python? Jul 13, 2025 am 01:46 AM

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.

Python for loop over a tuple Python for loop over a tuple Jul 13, 2025 am 02:55 AM

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.

What are python default arguments and their potential issues? What are python default arguments and their potential issues? Jul 12, 2025 am 02:39 AM

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.

See all articles