在 Ubuntu 中使用 FastAPI 创建一个简单的 Web 应用程序

FastAPI 是一个现代、快速且基于 Python 的 Web 框架,特别适合构建 API。本文将指导你如何在 Ubuntu 系统中安装 FastAPI 并创建一个简单的"Hello World"应用。


1. 安装必要的软件和依赖

在开始之前,请确保你的系统已经安装了以下工具:

  • Python(版本 >= 3.6)
  • pip(Python 的包管理器)

1.1 安装 Python 和 pip

如果你尚未安装 Python,可以使用以下命令进行安装:

bash 复制代码
sudo apt update && sudo apt install python3 python3-pip

2. 创建并激活虚拟环境(可选但推荐)

为了保持项目依赖的隔离性,建议创建一个虚拟环境。你可以使用 venvvirtualenv

2.1 使用 venv 创建虚拟环境

bash 复制代码
python3 -m venv my-fastapi-project

2.2 激活虚拟环境

bash 复制代码
source my-fastapi-project/bin/activate

激活后,你的终端会显示 (my-fastapi-project),表示你已经进入虚拟环境。


3. 安装 FastAPI 和依赖

在虚拟环境中安装 FastAPI 和 uvicorn(FastAPI 的 ASGI 服务器):

bash 复制代码
pip install fastapi uvicorn[standard]

4. 创建一个简单的 FastAPI 应用

4.1 创建项目结构

在当前目录下创建以下文件和文件夹:

复制代码
my-fastapi-project/
├── app/
│   ├── main.py
│   └── models/
│       └── __init__.py
└── requirements.txt

4.2 编写 main.py

app/main.py 文件中添加以下代码:

python 复制代码
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def root():
    return {"message": "Hello World!"}

@app.get("/items/{item_id}")
async def read_item(item_id: int):
    return {"item_id": item_id, "name": "Example Item"}

4.3 添加依赖到 requirements.txt

在项目根目录下创建一个 requirements.txt 文件,并添加以下内容:

复制代码
fastapi==0.68.0
uvicorn[standard]==0.15.0
python-multipart==0.2.0

5. 运行 FastAPI 应用

5.1 启动服务器

在项目根目录下,运行以下命令启动 FastAPI 服务器:

bash 复制代码
uvicorn app.main:app --reload
  • --reload:启用自动重新加载功能,当你修改代码时,服务器会自动重启。

5.2 访问应用

打开浏览器或使用 curl 命令访问以下地址:

  • 主页:http://localhost:8000/
  • 测试 API 端点:http://localhost:8000/items/1

输出示例:

bash 复制代码
{
    "message": "Hello World!"
}

6. 验证安装和依赖

如果你有任何问题,可以验证 FastAPI 和 uvicorn 是否正确安装:

bash 复制代码
pip freeze | grep fastapi

如果输出类似以下内容,则表示安装成功:

复制代码
fastapi==0.68.0

7. 总结

通过以上步骤,你已经在 Ubuntu 系统中成功创建并运行了一个简单的 FastAPI 应用。FastAPI 的优势在于其高性能和易用性,特别适合构建现代化的 Web API。

如果你还想探索更多功能(如 API 文档、数据验证、认证等),可以参考 FastAPI 官方文档

祝你在使用 FastAPI 进行开发时一切顺利!

相关推荐
wenzhangli79 分钟前
Ooder A2UI 核心架构深度解析:WEB 拦截层的设计与实现
前端·架构
前端百草阁33 分钟前
【前端性能优化全链路指南】从开发编写到构建运行的多维度实践
前端·性能优化
Frank_refuel39 分钟前
终端环境下:Ubuntu 22.04.1 安装 MySQL 数据库
数据库·mysql·ubuntu
女生也可以敲代码1 小时前
AI时代下的50道前端开发面试题:从基础到大模型应用
前端·面试
ZhengEnCi1 小时前
M5-markconv自定义CSS样式指南 📝
前端·css·python
IT_陈寒1 小时前
SpringBoot自动配置的坑差点让我加班到天亮
前端·人工智能·后端
xingpanvip1 小时前
星盘接口开发文档:星相日历接口指南
android·开发语言·前端·css·php·lua
@PHARAOH2 小时前
WHAT - GitLens supercharged 插件
前端
TT模板2 小时前
苹果cms整合西瓜播放器XGplayer插件支持跳过片头尾
前端·html5
Yoyo25年秋招冲冲冲2 小时前
【亲测可用】ubuntu系统下安装Openclaw+配置飞书
linux·ubuntu·ai·飞书·openclaw