# uvicorn

***

**1. Basic HTTP Server:**

```python
from fastapi import FastAPI, Request
app = FastAPI()

@app.get("/")
async def root(request: Request):
    return {"message": "Hello, World!"}
```

**2. Serve Static Files:**

```python
from fastapi.staticfiles import StaticFiles
app = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static")
```

**3. Error Handling:**

```python
from fastapi import FastAPI, HTTPException

app = FastAPI()

@app.get("/error")
async def error():
    raise HTTPException(status_code=404, detail="Not found")
```

**4. Query Parameter Validation:**

```python
from fastapi import FastAPI, Query

app = FastAPI()

@app.get("/query")
async def query(limit: int = Query(..., ge=0)):
    return {"limit": limit}
```

**5. Path Parameter Validation:**

```python
from fastapi import FastAPI, Path

app = FastAPI()

@app.get("/path/{id}")
async def path(id: int = Path(..., ge=1)):
    return {"id": id}
```

**6. JSON Request Body Validation:**

```python
from fastapi import FastAPI, Request

app = FastAPI()

@app.post("/json")
async def json(request: Request):
    data = await request.json()
    return {"data": data}
```

**7. Form Data Parsing:**

```python
from fastapi import FastAPI, Form

app = FastAPI()

@app.post("/form")
async def form(name: str = Form(...), age: int = Form(...)):
    return {"name": name, "age": age}
```

**8. File Upload:**

```python
from fastapi import FastAPI, File, UploadFile

app = FastAPI()

@app.post("/file")
async def file(file: UploadFile = File(...)):
    return {"filename": file.filename, "content_type": file.content_type}
```

**9. Basic Authentication:**

```python
from fastapi import FastAPI, Security, HTTPBasicCredentials

app = FastAPI()

@app.get("/auth")
async def auth(credentials: HTTPBasicCredentials = Security(...)):
    return {"username": credentials.username, "password": credentials.password}
```

**10. CORS Support:**

```python
from fastapi import FastAPI, Request

app = FastAPI()

@app.options("/{path:path}")
async def options(request: Request):
    headers = {
        "Access-Control-Allow-Origin": request.headers["Origin"],
        "Access-Control-Allow-Credentials": True,
        "Access-Control-Allow-Headers": "Authorization, Content-Type",
        "Access-Control-Allow-Methods": "GET, POST, OPTIONS"
    }
    return {"Allow": "GET, POST, OPTIONS"}, headers
```

**11. WebSockets:**

```python
from fastapi import FastAPI, WebSocket

app = FastAPI()

@app.websocket("/ws")
async def websocket(websocket: WebSocket):
    await websocket.accept()
    message = await websocket.receive_text()
    await websocket.send_text(f"Received: {message}")
```

**12. GraphQL Support:**

```python
from fastapi import FastAPI, Request, GraphQLHandler

app = FastAPI()
app.add_route("/graphql", GraphQLHandler(schema=schema))
```

**13. Swagger UI:**

```python
from fastapi import FastAPI, Request, Response

app = FastAPI()
app.mount("/docs", FastAPI(title="Documentation", openapi_url="/openapi.json"))
```

**14. Rate Limiting:**

```python
from fastapi import FastAPI, Request
from fastapi.responses import HTTP_429_TOO_MANY_REQUESTS

app = FastAPI()

@app.get("/")
async def root(request: Request):
    if await request.app.state.rate_limiter.check(request):
        return HTTP_429_TOO_MANY_REQUESTS
    return {"message": "Hello, World!"}
```

**15. Middleware:**

```python
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"]
)
```

**16. Request/Response Logging:**

```python
from fastapi.logger import logger

app = FastAPI()

@app.middleware("http")
async def log_request_response(request: Request, call_next):
    logger.info(f"Request: {request.method} {request.url}")
    response = await call_next(request)
    logger.info(f"Response: {response.status_code} {response.reason_phrase}")
    return response
```

**17. Custom Error Handlers:**

```python
from fastapi.exceptions import FastAPIException

app = FastAPI()

@app.exception_handler(FastAPIException)
async def custom_error_handler(request: Request, exc: FastAPIException):
    return {"error": exc.detail}
```

**18. Dependency Injection:**

```python
from fastapi import Depends, Request

app = FastAPI()

async def get_db_connection():
    return "DB connection"

@app.get("/db")
async def db(db_connection: str = Depends(get_db_connection)):
    return {"db_connection": db_connection}
```

**19. Background Tasks:**

```python
from fastapi import FastAPI, BackgroundTasks

app = FastAPI()

@app.post("/task")
async def task(background_tasks: BackgroundTasks):
    background_tasks.add_task(process_task, arg1, arg2)
```

**20. Event Handlers:**

```python
from fastapi import FastAPI, Event, HTTPException

app = FastAPI()

@app.on_event("startup")
async def startup_event():
    print("Startup event triggered")

@app.on_event("shutdown")
async def shutdown_event():
    print("Shutdown event triggered")

@app.get("/error")
async def error_handler():
    raise HTTPException(status_code=404, detail="Not found")
```
