使用 PyCharm 构建 FastAPI 项目:零基础入门 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 开发](#使用 PyCharm 构建 FastAPI 项目:零基础入门 Web API 开发)
      • [一 FastAPI 依赖简述](#一 FastAPI 依赖简述)
      • [二 使用 PyCharm 创建 python 应用](#二 使用 PyCharm 创建 python 应用)
        • [1 使用 Pure Python](#1 使用 Pure Python)
        • [2 使用 FastAPI 插件](#2 使用 FastAPI 插件)
      • [三 FastAPI 安装](#三 FastAPI 安装)
        • [1 安装 FastAPI](#1 安装 FastAPI)
        • [2 安装 ASGI 服务器](#2 安装 ASGI 服务器)
      • [四 FastAPI 示例](#四 FastAPI 示例)
      • [五 启动应用](#五 启动应用)
      • [六 检查运行状态](#六 检查运行状态)
      • [七 交互式 API 文档](#七 交互式 API 文档)
        • [1 Swagger UI](#1 Swagger UI)
        • [2 ReDoc 文档](#2 ReDoc 文档)
      • [八 源码地址](#八 源码地址)

一 FastAPI 依赖简述

FastAPI 核心技术栈 说明
Python 建议版本 python 3.6+
Starlette 用于处理 Web 部分
Pydantic 用于处理数据验证和解析

二 使用 PyCharm 创建 python 应用

File -> New Project... ,本文使用 Pure Python 创建应用。

1 使用 Pure Python
2 使用 FastAPI 插件

三 FastAPI 安装

1 安装 FastAPI

要安装 FastAPI,可以运行以下命令。

sh 复制代码
# 本文安装的是 fastapi[standard]
pip install "fastapi[standard]"
pip install "fastapi[all]"
pip install fastapi
2 安装 ASGI 服务器

ASGI 服务器是用来运行应用程序的,推荐在生产环境中使用 Uvicorn

sh 复制代码
pip install "uvicorn[standard]"

安装 FastAPI 一般会带上 uvicorn,当然你也可以用其他 ASGI 服务器。

四 FastAPI 示例

下面是一个简单的 FastAPI 示例,将这段代码拷贝到 main.py 中 。

python 复制代码
from typing import Union

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    price: float
    is_offer: Union[bool, None] = None

@app.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}

五 启动应用

要运行应用程序,使用以下命令启动服务器:

sh 复制代码
uvicorn main:app --reload

命令说明:

  • main:指向 main.py 文件(即 Python 模块)。
  • app:在 main.py 文件中通过 app = FastAPI() 创建的应用实例。
  • --reload:开启代码热重载,使得修改代码后服务器自动重启(适用于开发环境)。

运行日志

lua 复制代码
INFO:     Will watch for changes in these directories:[xxx]
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C 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?q=somequery 来验证应用的工作情况,返回 JSON。

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 文档

相关推荐
一木之林13 小时前
Python.五.(一)--1. 并发编程、异步IO与多进程
后端
feng尘13 小时前
# 彻底搞懂 ReentrantLock 与 tryLock:从秒杀实战到 AQS 独占模式源码剖析
后端
啷里格啷14 小时前
Linux进程管理完全指南:从基础到云原生编排
后端·架构
洛阳泰山14 小时前
AI 应用层被 Python 卷成红海,为什么我偏要用 Java 造一个 RAG + 工作流引擎?
java·人工智能·后端
Wz_z_z_z14 小时前
SpringBoot Actuator 泄露挖掘实战:从 /env 到 heapdump
后端
9i编程14 小时前
工具是编程的铠甲(下篇):从文件对比、全文搜索到数据库设计
后端·openai·ai编程
思考着亮14 小时前
4.Redis 核心概念与实战深度
后端
北斗落凡尘14 小时前
如何使用LangGraph(1)
python·langchain
Java编程爱好者14 小时前
Reactor 网络模型演进:图解 7 种 Reactor 网络模型
后端
YuePeng14 小时前
一个注解起家,25 个模块收尾:Erupt 的生态版图长这样
后端·github