I'm using Swagger Editor to generate a Python Flask server, I followed the Connexion document but there's a problem:
I defined the following response in the swagger YAML file:
responses:
'200':
description: successful operation
schema:
type: object
required:
- firstname
- lastname
properties:
firstname:
type: string
lastname:
type: string
What I expected is to return the following response:
{
"firstname": "Jane",
"lastname" : "Doe"
}
However, the database API returns a much bigger dataset, for example:
user=db.get_user_info()
pprint.pprint(user)
{
"firstname" : "Jane",
"middlename": "foo",
"lastname" : "Doe",
"age" : "25",
"sex" : "male",
...
}
To return the response I expected, I have 2 solutions, but neither of them are perfect:
Solution 1:
Manually define a smaller dataset, for example:
user_response = {
"firstname" = user["firstname"],
"lastname" = user["lastname"]
}
return user_responose
But obviously, for each response I have to hard code a variable_response, which means I have to maintain the response properties in 2 places (both swagger YAML and the code).
Solution 2:
The models are generated by swagger codegen, so I have to access the models and try to get the response properties, for example, the user model probably defined like this:
self.swagger_types = {
'firstname': str,
'lastname': str,
}
This could be easy but in reality the response properties have lots of $ref and there are always $ref inside $ref. I can't find a way to get the all the properties easily.
So my question is, what is the best solution?
Thanks a lot!
Connexion does not influence in how you can do what you want here. What you could do is to access your Swagger definitions in your handler and then check which fields need to be returned.
About the how to de-ref the JSON objects. You can see here how Connexion does that.
Connexion will validate the response of your endpoints if you set the parameter validate_responses=True
in your connexion.App#add_api
method call. So don't worry if your schema does not match with the spec, Connexion will throw an exception at runtime. Remember to write tests for your code, so you will get this kind of errors before deploying your app to production.