python开发接口uvicorn方法启动FastAPI,postman调用接口

python开发接口uvicorn方法启动FastAPI,postman调用接口

FastAPI 基于 ASGI 规范(异步网关接口),其应用实例 app 是一个ASGI 应用对象,而非普通函数。

通过 ASGI 服务器(uvicorn/gunicorn)启动应用,而非直接调用 app()

安装

复制代码
#pip install fastapi
#pip install uvicorn

uvicorn main:app --host 0.0.0.0 --port 8000

案例

复制代码
# main.py
from fastapi import FastAPI
import uvicorn

app = FastAPI()


# 示例1:GET接口(无参数)
@app.get("/hello")
def hello():
    return {"message": "Hello FastAPI"}

# 示例2:GET接口(带查询参数)
@app.get("/user/{user_id}")
def get_user(user_id: int, name: str = None):
    return {"user_id": user_id, "name": name}

# 示例3:POST接口(带JSON参数)
@app.post("/create-user")
def create_user(user: dict):
    return {"code": 200, "data": user, "msg": "创建成功"}

if __name__ == "__main__":
    # 启动服务:host=0.0.0.0 允许外部访问,port=8000
    uvicorn.run(app, host="0.0.0.0", port=8000)

启动

命令行启动(推荐)

uvicorn main:app --host 0.0.0.0 --port 8000

复制代码
postman调用接口

http://127.0.0.1:8000/hello

相关推荐
神秘的猪头9 分钟前
新版 LangChain Agent 核心架构:State、Context、ToolRuntime 与 Middleware
langchain·llm·fastapi
神秘的猪头9 分钟前
新版 LangChain Agent 入门:从 `bind_tools + while` 到 `create_agent`
langchain·fastapi
神秘的猪头15 分钟前
把新版 LangChain Agent 做成真正应用:Memory、Streaming、SSE 与 Structured Output
langchain·fastapi
用户9385156350720 分钟前
Text2SQL 实战:用 DeepSeek 大模型实现自然语言查询 SQLite 数据库
python·sqlite
2601_9620996835 分钟前
Python环境下中文分词实现与应用探索
python·自然语言处理·中文分词·jieba·开源社区
2601_9669496543 分钟前
批量获取多只股票五档盘口的极简方案:QuantDash Python SDK 实战指南
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
用户0190275816143 分钟前
如何用 Python 监控 A 股涨停跌停与封板/炸板?
python
Lyra_Infra1 小时前
云效主机部署场景下 Python 服务生命周期问题复盘
后端·python
刀鋒偏冷1 小时前
CentOS 7 配置 Python 3.12.4 + RTX 4090 深度学习环境全记录
python·深度学习·centos
DreamLife☼1 小时前
Agent开发环境搭建完全指南
python·docker·typescript·node·工业知识点