问小白 wenxiaobai
资讯
历史
科技
环境与自然
成长
游戏
财经
文学与艺术
美食
健康
家居
文化
情感
汽车
三农
军事
旅行
运动
教育
生活
星座命理

使用PyCharm构建FastAPI项目:零基础入门Web API开发

创作时间:
作者:
@小白创作中心

使用PyCharm构建FastAPI项目:零基础入门Web API开发

引用
CSDN
1.
https://blog.csdn.net/u014394049/article/details/143381461

FastAPI是一个现代、快速(高性能)的Web框架,用于构建API,基于Python类型提示。它具有以下特点:

  1. 快速:高性能,接近于C++/Go的性能
  2. 减少人为错误:使用类型提示进行数据验证
  3. 易于使用:自动为API生成交互式文档
  4. 类型安全:基于Python的类型提示系统

本文提供了一份完整的FastAPI入门指南,涵盖从环境搭建、依赖安装到创建并运行一个简单的FastAPI应用的各个步骤。通过FastAPI和Uvicorn,开发者可以快速构建现代化的Web API。文章还介绍了如何使用PyCharm创建Python项目、如何编写API路由和数据模型,并通过Swagger UI和ReDoc 自动生成交互式API文档进行测试。本文适合初学者了解FastAPI的基础知识,并快速上手开发高效的Web API。

一、FastAPI依赖简述

FastAPI的核心技术栈及其说明如下:

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

二、使用PyCharm创建Python应用

在PyCharm中创建一个新的Python项目:

  1. 使用Pure Python

    选择"Pure Python"创建应用。

  2. 使用FastAPI插件

    如果安装了FastAPI插件,也可以通过插件创建项目。

三、FastAPI安装

  1. 安装FastAPI

    可以使用以下命令安装FastAPI:

    pip install "fastapi[standard]"
    pip install "fastapi[all]"
    pip install fastapi
    
  2. 安装ASGI服务器

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

    pip install "uvicorn[standard]"
    

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

四、FastAPI示例

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

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}

五、启动应用

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

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 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:

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

© 2023 北京元石科技有限公司 ◎ 京公网安备 11010802042949号