FastAPI Local Development Guide

Run high-performance Python APIs on localhost:8000 using FastAPI and Uvicorn, with built-in OpenAPI documentation.


FastAPI is a modern Python asynchronous API framework that uses type hints to automatically generate OpenAPI/Swagger documentation. It runs locally via Uvicorn on the default http://localhost:8000.

Quick Start

pip install fastapi uvicorn[standard]

main.py:

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"message": "Hello from FastAPI on localhost"}
uvicorn main:app --reload

Access http://localhost:8000.

Automatic API Documentation

PathDescription
/docsSwagger UI
/redocReDoc

For example, http://localhost:8000/docs

Change Port

uvicorn main:app --reload --port 8080

Comparison with Django/Flask

FrameworkDefault PortFocus
FastAPI8000Asynchronous REST API
Django8000Full-stack + Admin
Flask5000Synchronous microframework

Frontend Integration

Vite (5173) requests FastAPI (8000) require CORS:

from fastapi.middleware.cors import CORSMiddleware

app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:5173"],
    allow_methods=["*"],
    allow_headers=["*"],
)

Frequently Asked Questions

Port 8000 Conflicts with Django
If running Django and FastAPI simultaneously, change the port for one of them.

—reload Not Working
Ensure you are modifying the entry module; on Windows, you may need watchfiles.

Summary

Run FastAPI locally with uvicorn main:app --reload, defaulting to http://localhost:8000, with /docs providing interactive API documentation.

访客计数:------ Best viewed in Netscape Navigator · 800×600 © LocalHost Run