fastapi框架

Ryder 2025-6-15 19 6/15

pip install fastapi

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

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

from fastapi import FastAPI

app = FastAPI()

@app.get("/items/{item_id}") 
def read_item(item_id):
    return {"item_id": item_id}

给某个路径参数传递某几个固定的有效值

from enum import Enum
from fastapi import FastAPI


class Hjx_Class_name(str, Enum):
    Name = 'huangjunx'
    Year = 18
    Id = '20153201072'
    student = True


app = FastAPI()


@app.get('/hjx/{hjx_man}')
def root(hjx_man: Hjx_Class_name):
    return {'status': hjx_man}

请求体(Request Body)
当您需要将数据从客户端(例如浏览器)发送到API时,可以将其作为 “请求体” 发送。

请求体是客户端发送到您的API的数据。 响应体是您的API发送给客户端的数据。

API几乎总是必须发送一个响应体,但是客户端并不需要一直发送请求体。

定义请求体,需要使用 Pydantic 模型。注意以下几点

不能通过GET请求发送请求体
发送请求体数据,必须使用以下几种方法之一:POST(最常见)、PUT、DELETE、PATCH

from fastapi import FastAPI
from pydantic import BaseModel


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


app = FastAPI()


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

声明参数的类型为你创建的模型 Item

这样当你使用postman选择post方法访问链接并传递一个值为

{
“name”: “Foo”,
“price”: 45.2
}

的请求体之后,会得到输出

{
“name”: “Foo”,
“price”: 45.2
}

 

- THE END -

Ryder

6月15日22:35

最后修改:2025年6月15日
0

非特殊说明,本博所有文章均为博主原创。

共有 0 条评论