Skip to content
Advertisement

How do I get the Swagger-generated Python client to work?

I have generated the python client and server from https://editor.swagger.io/ – and the server runs correctly with no editing, but I can’t seem to get the client to communicate with it – or with anything.

I suspect I’m doing something really silly but the examples I’ve found on the Internet either don’t work or appear to be expecting that I understand how to craft the object. Here’s my code (I’ve also tried sending nothing, a string, etc):

import time
import swagger_client
import json
from swagger_client.rest import ApiException
from pprint import pprint

# Configure OAuth2 access token for authorization: petstore_auth
swagger_client.configuration.access_token = 'special-key'
# create an instance of the API class
api_instance = swagger_client.PetApi()
d = '{"id": 0,"category": {"id": 0,"name": "string"},"name": "doggie","photoUrls": ["string"],  "tags": [ {      "id": 0,      "name": "string"    }  ],  "status": "available"}'
python_d = json.loads(d)
print( json.dumps(python_d, sort_keys=True, indent=4) )
body = swagger_client.Pet(python_d) # Pet | Pet object that needs to be added to the store

try:
    # Add a new pet to the store
    api_instance.add_pet(body)
except ApiException as e:
    print("Exception when calling PetApi->add_pet: %sn" % e)

I’m using python 3.6.4 and when the above runs I get:

Traceback (most recent call last):
  File "petstore.py", line 14, in <module>
    body = swagger_client.Pet(python_d) # Pet | Pet object that needs to be added to the store
  File "/Users/bombcar/mef/petstore/python-client/swagger_client/models/pet.py", line 69, in __init__
    self.name = name
  File "/Users/bombcar/mef/petstore/python-client/swagger_client/models/pet.py", line 137, in name
    raise ValueError("Invalid value for `name`, must not be `None`")  # noqa: E501
ValueError: Invalid value for `name`, must not be `None`

I feel I’m making an incredibly basic mistake, but I’ve literally copied the JSON from https://editor.swagger.io/ – but since I can’t find an actually working example I don’t know what I’m missing.

Advertisement

Answer

The Python client generator produces object-oriented wrappers for the API. You cannot post a dict or a JSON string directly, you need to create a Pet object using the generated wrapper:

api_instance = swagger_client.PetApi()
pet = swagger_client.Pet(name="doggie", status="available",
                         photo_urls=["http://img.example.com/doggie.png"],
                         category=swagger_client.Category(id=42))

response = api_instance.add_pet(pet)
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement