DeanWay / fastapi-versioning

api versioning for fastapi web applications
MIT License
644 stars 63 forks source link

Extend documentation in using middleware with versioning #14

Open datenwort opened 4 years ago

datenwort commented 4 years ago

I recently found out that the use of middleware has to be added to the versioning_app otherwise it will not work. Should be added to the documentation

import time
from fastapi import FastAPI, Request
from fastapi_versioning import VersionedFastAPI, version

app = FastAPI(title='My App')

@app.get('/greet')
@version(1, 0)
def greet():
  return 'Hello'

@app.get('/greet')
@version(1, 1)
def greet():
  return 'Hi'

app = VersionedFastAPI(app)

@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
    """Middleware to set response time."""
    start_time = time.time()
    response = await call_next(request)
    process_time = time.time() - start_time
    response.headers["X-Process-Time"] = str(process_time)
    return response