Dorthu / openapi3

A Python3 OpenAPI 3 Spec Parser
BSD 3-Clause "New" or "Revised" License
118 stars 47 forks source link

Select Server fo request #106

Closed mariofix closed 1 year ago

mariofix commented 1 year ago

Awesome library, thanks!

The file i'm trying to read has two servers in it

servers:
  - url: 'https://www.flow.cl/api'
    description: Production server (uses live data)
  - url: 'https://sandbox.flow.cl/api'
    description: Sandbox server (uses test data)

But i noticed in _get_callable that you select the first one in the array

        base_url = self.servers[0].url

is there another way to select the server to send the request?

commonism commented 1 year ago

Your example basically mirrors a server definition as shown in the swagger doc. Yet - it does not work. A client is free to use any server defined, random.choice would be as valid as [0]. If you want to use a single description document to address different server backends - such as live and development, the use of server-variables is required.

e.g.

openapi: 3.0.0
servers:
  - url: 'https://{host}.flow.cl/api'
    variables:
      host:
        enum:
          - sandbox
          - www
        default: sandbox  

The client has to support server-variables. You have to provide the server-variables to the client upon instantiation, such as

api = OpenAPI(…, server_variables={"host":"www"})

next, client has to create the url using the provided variables, default values and format.

So overall, it's possible, but I do not know about the implementation status of server-variables wrt. to client libraries/generators, expect it to be marginal/niche.

Additionally it is possible to specify "servers" on a PathItem and Operation scope, but this won't help with your use-case.

I think you'll be better of to modify servers to match your requirements before passing the description document to the client/library.

mariofix commented 1 year ago

Thanks, yeah, I noticed they do not conform to the standard, so I just created one file for sandbox and another for live.