What is the best way to run REST API versions with

2019-03-30 16:00发布

问题:

I am creating a REST API in Python Flask and would like to know what are the options to create a versionable API that references a specific git tag.

What I want to be able to do is specify a version of the API e.g. http://myapiserver.com/flaskapp/query/listcontent?version=1.1

And then have the version link back to code that I have tagged in git as v1.1.

What are the options and what is the best way to manage this?

回答1:

I can think of two ways to support a versioned APIs, but neither involves the app messing with its own git repository like you seem to suggest in your question.

Let's say, for example, that you have two versions of an API, v1.0 and v1.1.

The straightforward way is to have the two versions installed on different directories running, each listening on a different localhost port or unix socket. The routes on these two versions do not need to have versions embedded, so for example, both can have a /users endpoint. What ties everything together is a reverse proxy (like nginx) which exposes these two apis with external URLs that use versioning, which maps /v1.0/users to the v1.0 server and /v1.1/users to the v1.1 server.

Another option is to have your v1.1 server respond to both the v1.1 endpoints and the v1.0 endpoints. In this case the server will have the versions in the routes, so the v1.1 server will have both a /v1.0/users and /v1.1/users. This would seem like a complication at first, since each new API version will have to support all of the old ones, but it can also be seen as an optimization, because for API endpoints that don't change or have minimal differences between versions you can handle them with the same code:

@app.route('/<version>/users')
def users(version):
    # do something
    return jsonify(response)