fastapi:第一章:安装fastapi
一,官网:
https://fastapi.tiangolo.com/
源码:
https://github.com/fastapi/fastapi
二,安装库
创建虚拟环境:
$ /usr/local/soft/python3.10.19/bin/python3 -m venv venv
启用环境:
$ source venv/bin/activate
安装FastAPI和uvicorn服务器
# 安装FastAPI和uvicorn服务器
pip install fastapi uvicorn
三,代码中引用
# main.py - 第一个FastAPI程序
from fastapi import FastAPI
# 创建FastAPI应用实例
# 可以设置标题、描述、版本等元数据
app = FastAPI(
title="我的第一个FastAPI应用",
description="这是一个学习FastAPI的示例项目")
# 定义根路径GET请求
@app.get("/")
async def root():
"""
根路径处理函数
返回欢迎信息
"""
return {
"message": "Hello FastAPI!"
}
# 定义简单的带参数接口
@app.get("/greet/{name}")
def greet(name: str, age: int = None):
"""
问候接口
- **name**: 用户名(路径参数)
- **age**: 年龄(可选查询参数)
"""
message = f"Hello, {name}!"
if age:
message += f" 你今年可都{age}岁了."
return {"message": message}
四,运行
$ uvicorn main:app --reload
INFO: Will watch for changes in these directories: ['/data/python/fastapi/demo1']
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [23782] using StatReload
INFO: Started server process [23792]
INFO: Waiting for application startup.
INFO: Application startup complete.
五,测试效果:

六,查看文档:
查看文档:
http://localhost:8000/docs#/
效果图:

浙公网安备 33010602011771号