Search code examples
pythonversionfastapi

How do I output the version of my FastAPI app?


I have an application in FastAPI.

app = FastAPI( version="v0.1.0.0" )

I want to output the version of my application in a separate endpoint so another application knows what version this application is.

I want to build something like this:

@app.get("/v0/version"):
async def api_version():
     return {"version": app_version}

where the above would return {"version": 0.1.0.0"}.

However, I am not sure what to specify in the app_version field.


Solution

  • You were nearly there...

    It's an attribute on the FastAPI object: https://github.com/tiangolo/fastapi/blob/master/fastapi/applications.py#L102

    So you can:

    from fastapi import FastAPI
    
    app = FastAPI(version="v0.1.0.0")
    
    @app.get("/v0/version"):
    async def version():
        return {"version": app.version}
    

    To add this to all your APIs...

    Based on this answer (https://stackoverflow.com/a/70563827/202168) and this answer (https://stackoverflow.com/a/66596529/202168) I think we can make a custom router class like this:

    from fastapi import FastAPI, APIRouter, Request
    
    
    async def _version(request: Request):
        return {"version": request.app.version}
    
    
    class VersionedAPIRouter(APIRouter):
        def __init__(self, *args, **kwargs):
            super().__init__(*args, *kwargs)
            self.add_api_route(
                "/version",
                _version,
                methods=["GET"],
            )
    
    
    v0_router = VersionedAPIRouter(
        prefix="/v0",
    )
    
    app = FastAPI(version="v0.1.0.0")
    app.include_router(v0_router)