Install uv for Python package and venv manager
brew install uv
Initialize UV and install FastAPI
Create project folder and move into it
mkcd myproject
Initialize uv inside it
uv init
Add my packages, e.g., FastAPI
uv add fastapi --extra standard
Setup project structure
Create folder /app
mkcd app
Add file __init__.py inside /app
Add file main.py inside /app
touch __init__.py
touch main.py
Run fastapi
uv run fastapi dev
https://fastapi.tiangolo.com/tutorial/first-steps/
Sample API, GET and POST
from typing import Union
from pydantic import BaseModel
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from datetime import datetime
app = FastAPI()
# Not safe! Add your own allowed domains
origins = [
"*",
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Define what you will receiving in request
class TypePayload(BaseModel):
content: str
# Example GET route for app
@app.get("/")
def read_root():
return {"Message": "Hello World! FastAPI is working."}
# Example POST route for app
@app.post("/getdata")
async def create_secret(payload: TypePayload):
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
Top comments (0)