如何生成一个最简单的 FastAPI 文件?
FastAPI官方文档:https://fastapi.tiangolo.com/zh/tutorial/first-steps/
# -*- coding: utf-8 -*-
"""
@file: main.py
@author: CSDN-北极的三哈
@time: 2024/8/27 22:11
@email:flymeawei@163.com
@software: PyCharm2024.2
"""
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
1、导入 FastAPI
from fastapi import FastAPI

2、创建一个FastAPI实例
app = FastAPI()

这里的变量 app 会是 FastAPI 类的一个「实例」。这个实例将是创建你所有 API 的主要交互对象。这个 app 同样在如下命令中被 uvicorn 所引用:uvicorn main:app --reload
3、定义一个路径操作装饰器
路径:URL中从第一个 / 起的后半部分。
操作:指的是一种 HTTP方法」
装饰器:@something
@app.get("/")
@app.get("/")告诉 FastAPI 在它下方的函数负责处理如下访问请求:
- 请求路径为
/ - 使用
get操作

也可以使用其他的操作:
-
@app.post()
-
@app.put()
-
@app.delete()
-
@app.options()
-
@app.head()
-
@app.patch()
-
@app.trace()
4、定义路径操作函数
路径:是 /。
操作:是 get。
函数:是位于 @app.get("/") 下方。
async def root():
return {"message": "Hello World"}

5、返回内容
async def root():
return {"message": "Hello World"}
可以返回一个 dict、list,像 str、int 一样的单个值,等等,还可以返回 Pydantic 模型。还有许多其他将会自动转换为 JSON 的对象和模型(包括 ORM 对象等)。

6、运行开发服务器
uvicorn main:app --reload
打开浏览器访问 http://127.0.0.1:8000

http://127.0.0.1:8000/docs交互式 API 文档

总结:
- 导入
FastAPI。 - 创建一个
app实例。 - 编写一个路径操作装饰器(如:
@app.get("/"))。 - 编写一个路径操作函数(如上面的
def root(): ...)。 - 运行开发服务器(如:
uvicorn main:app --reload)




![[C++番外] 抛异常](https://i-blog.csdnimg.cn/direct/05a040741d18412d8e81d632e4502405.png)













![Python -- GUI图形界面编程—GUI编程实例 博主也在持续学习中[ 持续更新中!!! 欢迎白嫖 ]](https://i-blog.csdnimg.cn/direct/455887575f62410595c38fbb8c157aa3.png)
