Upload
henning-jacobs
View
139
Download
3
Embed Size (px)
Citation preview
ConnexionSwagger-first with Python+FlaskPython Meetup Berlin [email protected] @try_except_
API First
● Define REST API before implementation
● API definition is contract between teams
● Includes validation & documentation
info: {title: "Pet Shop Example API", version: "0.1"}paths: /pets: get: operationId: app.get_pets parameters: - name: animal_type in: query type: string responses: 200: schema: type: array items: $ref: '#/definitions/Pet' /pets/{pet_id}: get: operationId: app.get_pet parameters: - name: pet_id in: path type: string required: true responses: 200: schema: $ref: '#/definitions/Pet' 404: description: Pet does not exist put: tags: [Pets] operationId: app.put_pet summary: Create or update a pet parameters: - name: pet_id in: path type: string required: true - name: body in: body schema: $ref: '#/definitions/Pet' responses: 200: description: Pet updated 201: description: New pet created delete: tags: [Pets] operationId: app.delete_pet summary: Remove a pet parameters: - name: pet_id in: path type: string required: true responses: 204: description: Pet was deleted 404: description: Pet does not exist
info: {title: "Pet Shop Example API", version: "0.1"}paths: /pets: get: operationId: app.get_pets parameters: - name: animal_type in: query type: string responses: 200: schema: type: array items: $ref: '#/definitions/Pet' /pets/{pet_id}: get: operationId: app.get_pet parameters: - name: pet_id in: path type: string required: true responses: 200: schema: $ref: '#/definitions/Pet' 404: description: Pet does not exist put: tags: [Pets] operationId: app.put_pet summary: Create or update a pet parameters: - name: pet_id in: path type: string required: true - name: body in: body schema: $ref: '#/definitions/Pet' responses: 200: description: Pet updated 201: description: New pet created delete: tags: [Pets] operationId: app.delete_pet summary: Remove a pet parameters: - name: pet_id in: path type: string required: true responses: 204: description: Pet was deleted 404: description: Pet does not exist
Connexion: UsagePETS = {}
def get_pets(): animal_type = flask.request.args.get('animal_type') return [pet for pet in PETS.values() if not animal_type or pet['animal_type'] == animal_type]
def get_pet(pet_id): pet = PETS.get(pet_id) return pet or ('Not found', 404)
# ...
app = connexion.App('myapp', port=8080, server='gevent')app.add_api('swagger.yaml')app.run()
HTTPie as REST client+ http PUT :8080/pets/1 name=foo animal_type=testHTTP/1.1 201 CREATEDContent-Length: 4Content-Type: application/jsonDate: Tue, 11 Aug 2015 16:34:06 GMT
+ http :8080/pets/1HTTP/1.1 200 OKContent-Length: 101Content-Type: application/jsonDate: Tue, 11 Aug 2015 16:34:06 GMT
{ "animal_type": "test", "created": "2015-08-11T16:34:06.410620Z", "id": "1", "name": "foo"}
Linksgithub.com/hjacobs/connexion-example
github.com/zalando/connexion
tech.zalando.com@try_except_