人流医院网站建设,信息科技公司网站,陕西省住房和城乡建设厅官网证件,做卡盟开端网站要多少钱使用 PyCharm 构建 FastAPI 项目#xff1a;零基础入门 Web API 开发
本文提供了一份完整的 FastAPI 入门指南#xff0c;涵盖从环境搭建、依赖安装到创建并运行一个简单的 FastAPI 应用的各个步骤。通过 FastAPI 和 Uvicorn#xff0c;开发者可以快速构建现代化的 Web API…使用 PyCharm 构建 FastAPI 项目零基础入门 Web API 开发
本文提供了一份完整的 FastAPI 入门指南涵盖从环境搭建、依赖安装到创建并运行一个简单的 FastAPI 应用的各个步骤。通过 FastAPI 和 Uvicorn开发者可以快速构建现代化的 Web API。文章还介绍了如何使用 PyCharm 创建 Python 项目、如何编写 API 路由和数据模型并通过 Swagger UI 和 ReDoc 自动生成交互式 API 文档进行测试。本文适合初学者了解 FastAPI 的基础知识并快速上手开发高效的 Web API。 文章目录 使用 PyCharm 构建 FastAPI 项目零基础入门 Web API 开发一 FastAPI 依赖简述二 使用 PyCharm 创建 python 应用1 使用 Pure Python2 使用 FastAPI 插件 三 FastAPI 安装1 安装 FastAPI2 安装 ASGI 服务器 四 FastAPI 示例五 启动应用六 检查运行状态七 交互式 API 文档1 Swagger UI2 ReDoc 文档 八 源码地址 一 FastAPI 依赖简述
FastAPI 核心技术栈说明Python建议版本 python 3.6Starlette用于处理 Web 部分Pydantic用于处理数据验证和解析
二 使用 PyCharm 创建 python 应用
File - New Project... 本文使用 Pure Python 创建应用。
1 使用 Pure Python 2 使用 FastAPI 插件 三 FastAPI 安装
1 安装 FastAPI
要安装 FastAPI可以运行以下命令。
# 本文安装的是 fastapi[standard]
pip install fastapi[standard]
pip install fastapi[all]
pip install fastapi2 安装 ASGI 服务器
ASGI 服务器是用来运行应用程序的推荐在生产环境中使用 Uvicorn。
pip install uvicorn[standard]安装 FastAPI 一般会带上 uvicorn当然你也可以用其他 ASGI 服务器。
四 FastAPI 示例
下面是一个简单的 FastAPI 示例将这段代码拷贝到 main.py 中 。
from typing import Unionfrom fastapi import FastAPI
from pydantic import BaseModelapp FastAPI()class Item(BaseModel):name: strprice: floatis_offer: Union[bool, None] Noneapp.get(/)
def read_root():return {Hello: World}app.get(/items/{item_id})
def read_item(item_id: int, q: Union[str, None] None):return {item_id: item_id, q: q}app.put(/items/{item_id})
def update_item(item_id: int, item: Item):return {item_name: item.name, item_id: item_id}五 启动应用
要运行应用程序使用以下命令启动服务器
uvicorn main:app --reload命令说明
main指向 main.py 文件即 Python 模块。app在 main.py 文件中通过 app FastAPI() 创建的应用实例。--reload开启代码热重载使得修改代码后服务器自动重启适用于开发环境。
运行日志
INFO: Will watch for changes in these directories:[xxx]
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRLC to quit)
INFO: Started reloader process [26400] using WatchFiles
INFO: Started server process [26404]
INFO: Waiting for application startup.
INFO: Application startup complete.六 检查运行状态
访问 http://127.0.0.1:8000/items/5?qsomequery 来验证应用的工作情况返回 JSON。
{item_id: 5,q: somequery
}七 交互式 API 文档
1 Swagger UI
访问 http://127.0.0.1:8000/docs看到自动生成的交互式 API 文档 Swagger UI 。 2 ReDoc 文档
访问 http://127.0.0.1:8000/redoc查看另一种自动生成的文档界面 ReDoc 。 八 源码地址
详情见GitHub FastApiProj
引用 FastAPI 文档