FastAPIenvironment-setup and project initialization

📂 Stage: Stage 1 - Rapid Foundation Building (Basics) 🔗 Related chapters: fastapi-intro-advantages · hello-world-app

Table of contents

Quickly start pre-check

FastAPI has very low machine requirements, and almost any computer that can run Python can easily get started.

Basic software and hardware requirements

  • Operating system: Windows 7 and above / macOS 10.12 and above / mainstream Linux distributions
  • Python version: 3.7 or above (the latest stable version of 3.10, 3.11 or 3.12 is highly recommended)
  • Hardware Configuration: 2GB RAM, 500MB free disk space, any modern CPU

First check if you have Python in your computer

Open a terminal (PowerShell or CMD for Windows, Terminal for Mac/Linux) and type the following commands to confirm the environment:

# Mac / Linux 一般用 python3
python3 --version   # 输出类似 Python 3.12.3
pip3 --version

# Windows 或配置过的系统可以直接用 python / pip
python --version
pip --version

If it prompts "command not found" or the version is too low, please install or upgrade Python according to your system:

  • Windows: Visit Python 官网 to download the installation package. Be sure to check "Add Python to PATH" during installation
  • Mac: It is recommended to use Homebrew to install:brew install python3
  • Linux: Use the built-in package manager, such as Ubuntu:sudo apt install python3 python3-pip

After the installation is complete, upgrade pip to the latest version to avoid strange compatibility issues in the future:

python3 -m pip install --upgrade pip   # 通用、安全的升级方式

Isolation environment: Python virtual environment

**Whether it is a practice project or a formal product, it is strongly recommended to use a virtual environment for development! ** The virtual environment can isolate the Python packages required by different projects, completely solving conflicts such as "Project A must use the old version, and Project B must use the new version."

Just use the official venv that comes with it

After Python 3.3, the standard library comes with a lightweight virtual environment toolvenv, no need to install anything additional.

Create and activate virtual environment

# 1. 创建一个文件夹作为项目根目录,比如 my-fastapi-demo
mkdir my-fastapi-demo
cd my-fastapi-demo

# 2. 在项目里创建一个叫 venv 的虚拟环境
python3 -m venv venv

# 3. 激活虚拟环境(注意系统差别)
# Windows PowerShell / CMD:
venv\Scripts\activate
# Mac / Linux:
source venv/bin/activate

After successful activation, the command line will appear in front of(venv)The logo indicates that you have entered the virtual environment, and all subsequent pip installations will only be installed in this environment.

Common management commands

# 退出虚拟环境(回到系统全局 Python)
deactivate

# 彻底删除这个虚拟环境(直接把 venv 文件夹删掉就好)
rm -rf venv            # Mac / Linux
rmdir /s venv         # Windows CMD

Core components: FastAPI and Uvicorn

FastAPI itself is a Web framework, responsible for defining interfaces, handling data verification, etc.; however, it does not "run" directly. It requires an ASGI server to receive network requests. The official partner is Uvicorn.

Installation method: choose as needed

# 轻量安装:FastAPI + 标准版 Uvicorn(已包含 websocket、静态文件等支持)
pip install fastapi uvicorn[standard]

# 全家桶:一次性装齐官方推荐的所有扩展(表单处理、模板、环境变量、邮箱校验等)
pip install "fastapi[all]"

# 锁定版本:如果你希望现在写的代码以后不会因为依赖升级而出错,可以指定版本号
pip install fastapi==0.110.0 uvicorn[standard]==0.29.0

💡 Suggestion: Use it when you first start learningfastapi[all]Very worry-free; use the accurate version when entering production projects +requirements.txtto control dependencies.

Use requirements.txt to lock the environment

When you share your project with others or deploy it on different computers, you canrequirements.txtQuickly restore an identical environment.

# 导出当前虚拟环境中的所有包名和版本
pip freeze > requirements.txt

After the other party gets the project, it only needs one line of command:

pip install -r requirements.txt

Standard project structure construction

A clear project structure allows you not to panic when the code increases, while laying the foundation for team collaboration and function expansion.

my-fastapi-demo/
├── app/                    # 应用主目录
│   ├── __init__.py         # 把 app 变成一个 Python 包
│   ├── main.py             # 入口文件,创建 FastAPI 实例、挂载路由
│   ├── api/                # 接口路由(可按版本拆分成 v1/v2)
│   │   ├── __init__.py
│   │   └── v1/
│   │       ├── __init__.py
│   │       └── hello.py
│   ├── schemas/            # Pydantic 模型(请求 / 响应数据校验)
│   │   ├── __init__.py
│   │   └── common.py
│   ├── config/             # 项目配置(读取环境变量等)
│   │   ├── __init__.py
│   │   └── settings.py
│   └── utils/              # 工具函数(日志、加密等)
│       └── __init__.py
├── tests/                  # 测试代码
│   ├── __init__.py
│   └── test_hello.py
├── venv/                   # 虚拟环境(不要提交到 Git)
├── requirements.txt        # 依赖清单
├── .gitignore              # 告诉 Git 哪些文件不用管
└── README.md               # 项目说明

Write these key documents first

1. .gitignore(Prevent junk files from being uploaded to Git)

# 虚拟环境
venv/
env/

# Python 缓存文件
__pycache__/
*.pyc
*.pyo
*.pyd

# IDE 配置
.vscode/
.idea/

# 敏感配置(比如数据库密码)
.env
.env.local

2. app/main.py(Application entrance)

from fastapi import FastAPI

app = FastAPI(
    title="我的FastAPI演示项目",
    description="这是一个用于演示environment-setup的标准FastAPI项目",
    version="0.1.0",
    openapi_url="/api/v1/openapi.json",   # OpenAPI 描述文档地址
    docs_url="/api/docs",                # Swagger UI 交互文档
    redoc_url="/api/redoc"               # ReDoc 样式文档
)

# 根路径,最简单的测试接口
@app.get("/")
async def root():
    return {"message": "欢迎来到FastAPI演示项目!"}

# 健康检查接口(将来部署时很有用)
@app.get("/health")
async def health_check():
    return {"status": "ok", "service": "FastAPI"}

VS Code development tool configuration

VS Code is the most popular editor for Python/FastAPI development. After installing the following plug-ins and doing a little configuration, development efficiency will be greatly improved.

1. Required plug-ins

Open the "Extension" icon on the left side of VS Code, search and install:

  • Python (official, providing basic functions such as syntax highlighting, debugging, code completion, etc.)
  • Pylance (powerful type checking and auto-completion)
  • Ruff (an extremely fast Python code inspection + formatting tool, which can replace Flake8, isort, etc.)

2. Add local configuration to the project

Create in the project root directory.vscode/settings.json, the contents are as follows:

{
    // 设置为当前项目里的虚拟环境 python 解释器
    "python.defaultInterpreterPath": "${workspaceFolder}/venv/bin/python",
    // Windows 下请用下面路径:
    // "python.defaultInterpreterPath": "${workspaceFolder}\\venv\\Scripts\\python.exe",

    // 启用 Ruff 来做代码检查与格式化
    "python.linting.enabled": true,
    "python.linting.ruffEnabled": true,
    "python.formatting.provider": "ruff",

    // 保存文件时自动整理格式和修复导入
    "editor.formatOnSave": true,
    "editor.codeActionsOnSave": {
        "source.fixAll.ruff": true
    }
}

In this way, everyone in the team can write code using unified rules, reducing "format wars".


One-click verification development environment

After all the parts are ready, start your first FastAPI application with the following command:

# 确保在项目根目录,且虚拟环境已激活
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000

Parameter explanation:

  • app.main:app→ module pathapp/main.pyFastAPI instance inapp
  • --reload→ Automatically restart as soon as the code is modified, suitable for development and debugging
  • --host 0.0.0.0→ Allow other devices in the same LAN to access (if you only want local access, you can remove it or use127.0.0.1
  • --port 8000→ Listen to port 8000 (if not written, the default is 8000)

Open the browser and see the effect

After the service is started, enter the following address in the browser:

  1. Root path:http://127.0.0.1:8000/→ Return{"message": "欢迎来到FastAPI演示项目!"}
  2. Health Check:http://127.0.0.1:8000/health→ Return to service status
  3. Swagger UI (interactive interface document):http://127.0.0.1:8000/api/docs→ Click “Try it out” to test the interface directly
  4. ReDoc (the document style is more concise):http://127.0.0.1:8000/api/redoc

If everything can be accessed normally, congratulations, FastAPI development environment-setup is successful!


High Frequency Trampling Guide

1. "Unable to load file..." when activating virtual environment on Windows

error message:无法加载文件 ...,因为在此系统上禁止运行脚本
Solution: Open PowerShell as administrator, execute the following line of commands, and then reactivate:

Set-ExecutionPolicy RemoteSigned -Scope CurrentUser

2. Prompt "Address already in use" when starting

error message:OSError: [Errno 48] Address already in use
Cause: Port 8000 is already occupied by other programs. Solution: Change the port to start, for example--port 8001, or find the program occupying the port in the terminal and close it (newbies are advised to change the port directly).

3. Not foundappmodule

error message:ModuleNotFoundError: No module named 'app'
Common reason: You are not in the project root directory (my-fastapi-demo) to run the command, but mistakenly enteredappfolder. Correct Practice: Make sure themy-fastapi-demoWhen this layer is started, there should be something in that directoryappfolder andvenvfolder.

4. The package is obviously installed, but it says it cannot be found when running it.

Mostly it's because the virtual environment is not activated. Every time you open a new terminal, remember to activate the virtual environment first (see the command before(venv)flag), and then run the project.


Summarize

Now that you have a clean, professional FastAPI development environment, the next step is to:

  1. Follow hello-world-app to write the first interface that can receive parameters and return data;
  2. Play with the built-in Swagger UI 交互式文档 more and experience the pleasure of one-click debugging;
  3. Follow this project structure and start building your own functional modules.
- Always operate in a virtual environment and do not pollute the system Python environment - Remember to update every time you install a new package`requirements.txt` - Sensitive configurations (passwords, keys) are placed in`.env`file and add it`.gitignore`