I’m looking to implement versioning on my FastAPI server and I’m not sure what the better approach is.
I have the following fictional endpoints which all fetch data
/user/stats
/user/projection
/team/stats
/team/projections
These are under 2 routers user
and team
, each within their own file user.py
and team.py
While it’s possible that breaking changes might affect every route on the router, it is more likely that changes to the endpoints will be done on an endpoint basis and not router basis. Also I only plan to have maybe a week or so of maintaining multiple versions before removing the old one.
So is it better to have the versioning happen at the router level, ie:
v1/user/stats
v1/user/projection
v1/team/stats
v1/team/projections
or at the endpoint level:
user/v1/stats
user/v1/projection
team/v1/stats
team/v1/projections
My issue with having it on the router level is that all the endpoints live in the same file, so I would need to essentially just copy paste the entire file into a new directory ie: v1/users.py -> v2/users.py
which feels bad to have that much duplicated code. Also if the version changes on the router, all of the endpoints are getting a new version regardless of if they change and the consumer needs to update all all of these on the FE. This could also lead to bloated version numbers if many changes are made to different endpoints.
If I version at the endpoint level I would have to have 2 versions in the same file, ie:
@router.get("/v1/stats", response_model=SomeModel_V1)
def v1_stats(...)
@router.get("/v2/stats", response_model=SomeModel_V2)
def v2_stats(...)
This seems better to me but I haven’t seen anything online that does this so I wanted to know if there was a best approach for this. I’ve looked at articles like https://medium.com/arionkoder-engineering/fastapi-versioning-e9f86ace52ca which does it at the router level but doesn’t cover best practices when a router has multiple routes. Any thoughts on any of this?