Skip to content

Instantly share code, notes, and snippets.

@rayyildiz
Last active March 23, 2024 15:48
Show Gist options
  • Save rayyildiz/9ab674121d14e6692dbb53e7452e3552 to your computer and use it in GitHub Desktop.
Save rayyildiz/9ab674121d14e6692dbb53e7452e3552 to your computer and use it in GitHub Desktop.

FastAPI Project

This is a simple FastAPI project with Docker and Sentry integration.

Project Setup

Make sure you have Python 3.10+ installed on your system. Also make sure Docker and Docker Compose are installed.

Local setup

Create a virtual environment and install the necessary dependencies.

python -m venv venv 
source venv/bin/activate 
pip install -r requirements.txt

Docker

Build the Docker image and launch the container.

docker build -t fastapi-app . 
docker run -p 8000:8000 fastapi-app

Your app will be running at http://127.0.0.1:8000.

Sentry

To set up Sentry error tracking, set the Sentry DSN in the environment.

export SENTRY_DSN=<your-sentry-dsn>
FROM python:3.10-slim
WORKDIR /apps
RUN apt-get update && apt-get install -y git
COPY ./requirements.txt requirements.txt
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
import os
import sentry_sdk
from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware
from starlette.requests import Request
# from app.api import api_router as apiv1
app = FastAPI(title="Demo API", openapi_url="/docs/v1/openapi.json")
sentry_dsn = os.getenv("SENTRY_DSN")
if sentry_dsn:
sentry_sdk.init(
sentry_dsn,
default_integrations=False,
)
@app.middleware("http")
async def sentry_exception(request: Request, call_next):
try:
response = await call_next(request)
return response
except Exception as e:
with sentry_sdk.push_scope() as scope:
scope.set_context("request", request)
scope.user = {
"ip_address": request.client.host,
}
sentry_sdk.capture_exception(e)
raise e
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/health")
def health_check():
return "Healthy"
# app.include_router(apiv1, prefix="/api/v1")
fastapi
sentry-sdk
pydantic
uvicorn
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment