FastAPI的路由

前言

回想一下我们在hello world程序里面做了哪些事情?

还是先把那段著名的程序的代码贴出来欣赏一下吧。

python 复制代码
from fastapi import FastAPI

app = FastAPI()


@app.get("/")
async def root():
    return {"message": "Hello World"}


@app.get("/hello/{name}")
async def say_hello(name: str):
    return {"message": f"Hello {name}"}
  1. from fastapi import FastAPI首先是导入了fastapi模块的FastAPI类,这个类的源码中我们可以看到,它是继承了Starlette
  2. app = FastAPI() 这段代码,是python中实例化了一个对象,赋值给了app变量
  3. @app.get("/") 这段代码很明显是在root()函数上增加了一个有参数的装饰器,这里面的参数就是路由 ,它的作用就是,当我们访问 / 这个地址的时候,服务端就会执行root这个函数,很明显这个函数返回的是一个字典,这个字典在返回时,服务内部将它转化成了一个JSON格式的字符串

支持的路由方法

也就是我们常说的HTTP请求方式。这里的路由方法指的就是一种 HTTP「方法」。

常用的有:

  • POST
  • GET
  • PUT
  • DELETE

不常使用的有

  • OPTIONS
  • HEAD
  • PATCH
  • TRACE
    在 HTTP 协议中,你可以使用以上的其中一种(或多种)「方法」与每个路径进行通信。

注意:在开发 API 时,你通常使用特定的 HTTP 方法去执行特定的行为。

通常使用:

  • POST:创建数据。
  • GET:读取数据。
  • PUT:更新数据。
  • DELETE:删除数据。

这是一种规范,当然,如果你不想遵守,比如你非要使用DELETE方法来进行更新数据,也不是不行,只是不规范。这不是强制要求。

相关推荐
曲幽4 小时前
不止于JWT:用FastAPI的Depends实现细粒度权限控制
python·fastapi·web·jwt·rbac·permission·depends·abac
曲幽1 天前
FastAPI分布式系统实战:拆解分布式系统中常见问题及解决方案
redis·python·fastapi·web·httpx·lock·asyncio
曲幽2 天前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
曲幽3 天前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
曲幽4 天前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
闲云一鹤5 天前
Python 入门(二)- 使用 FastAPI 快速生成后端 API 接口
python·fastapi
曲幽5 天前
FastAPI + Ollama 实战:搭一个能查天气的AI助手
python·ai·lora·torch·fastapi·web·model·ollama·weatherapi
百锦再6 天前
Django实现接口token检测的实现方案
数据库·python·django·sqlite·flask·fastapi·pip
Li emily6 天前
解决了股票实时数据接口延迟问题
人工智能·fastapi
司徒轩宇7 天前
FastAPI + Uvicorn 深度理解与异步模型解析
fastapi