Home >Backend Development >Python Tutorial >Python FastAPI quickstart in uv
Use uv to quickly build FastAPI applications
The following steps demonstrate how to use the uv tool to quickly create a simple FastAPI application containing GET and POST requests:
Initialization project:
<code class="language-bash">uv init uv add fastapi --extra standard</code>
Create project directories and files:
Create a folder named /app
and add two files __init__.py
and main.py
in it.
Write FastAPI code (main.py):
Copy the following code into the main.py
file:
<code class="language-python">from typing import Union from pydantic import BaseModel from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from datetime import datetime app = FastAPI() # 注意:生产环境中不要使用"*",请替换为你的允许域名 origins = [ "*", ] app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) class Stuff(BaseModel): content: str @app.get("/") def read_root(): return {"Message": "Hello World! FastAPI is working."} @app.post("/getdata/") async def create_secret(payload: Stuff): with open('output_file.txt', 'a') as f: now = datetime.now() formatted_date = now.strftime("%B %d, %Y at %I:%M %p") f.write(formatted_date + ": " + payload.content) f.write('\n') return payload.content</code>
Run FastAPI application:
<code class="language-bash">uv run fastapi dev</code>
This will start the development server. You can test GET requests by accessing http://127.0.0.1:8000
and send data to the /getdata/
endpoint using POST requests.
For more FastAPI tutorials, please refer to the official documentation: https://www.php.cn/link/b446e7f68f7a79f9de9d9f9ee9b764e8
This example demonstrates a simple GET and POST API. The /getdata/
endpoint will receive the content
field in the POST request and append the content to the output_file.txt
file, recording the timestamp. *Please note: In a production environment, `origins = [""]` is unsafe and must be replaced with your allowed domain name list. **
The above is the detailed content of Python FastAPI quickstart in uv. For more information, please follow other related articles on the PHP Chinese website!