httpfastapiapi-versioning

How to set FastAPI version to allow HTTP specifying version in accept header?


I am working on a project that requires to version FastAPI endpoints. We want to version the endpoint through HTTP accept header, for example:

headers={'Accept': 'application/json;version=1.0.1'}, 
headers={'Accept': 'application/json;version=1.0.2'}

Setting up the api version like this seem not work:

app = FastAPI(
        version=version,
        title="A title",
        description="Some description.",
    )

Does anyone know what else I need to do with this ?


Solution

  • Well maybe the version in path url could be better

    sub apps docs

    from fastapi import FastAPI
    
    app = FastAPI()
    v1 = FastAPI()
    
    @v1.get("/app/")
    def read_main():
        return {"message": "Hello World from api v1"}
    
    v2 = FastAPI()
    
    @v2.get("/app/")
    def read_sub():
        return {"message": "Hello World from  api v2"}
    
    app.mount("/api/v1", v1)
    app.mount("/api/v2", v2)
    

    You will see the auto docs for each app

    localhost:8000/api/v1/docs

    localhost:8000/api/v2/docs

    But you always get the headers in request

    from starlette.requests import Request
    
    from fastapi import FastAPI
    app = FastAPI()
    
    @app.post("/hyper_mega_fast_service")
    def fast_service(request: Request, ):
    
        aceept = request.headers.get('Accept')
    
        value = great_fuction_to_get_version_from_header(aceept)
        if value == '1.0.1': 
            "Do something"
            
        if value == '1.0.2': 
            "Do something"