[Quickstart] Python FastAPI with uv
Varun D

Varun D @varund

Joined:
Oct 3, 2023

[Quickstart] Python FastAPI with uv

Publish Date: Jan 13
7 0

Install uv for Python package and venv manager

UV Official Docs

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 (add this to app/main.py)

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
Enter fullscreen mode Exit fullscreen mode

[Optional] Setting up logging

import logging

# Get the univorn logger for the same CLI look
logger = logging.getLogger("uvicorn")

logger.info("GET request received at root endpoint")
logger.error("This is a test error.")
Enter fullscreen mode Exit fullscreen mode

Comments 0 total

    Add comment