Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add oas3 examples #622

Merged
merged 1 commit into from
Sep 13, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions examples/openapi3/basicauth/README.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
=======================
HTTP Basic Auth Example
=======================

Running:

.. code-block:: bash

$ sudo pip3 install --upgrade connexion[swagger-ui] # install Connexion from PyPI
$ ./app.py

Now open your browser and go to http://localhost:8080/ui/ to see the Swagger UI.

The hardcoded credentials are ``admin`` and ``secret``.
52 changes: 52 additions & 0 deletions examples/openapi3/basicauth/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
#!/usr/bin/env python3
'''
Connexion HTTP Basic Auth example

Most of the code stolen from http://flask.pocoo.org/snippets/8/

Warning: It is recommended to use 'decorator' package to create decorators for
your view functions to keep Connexion working as expected. For more
details please check: https://github.com/zalando/connexion/issues/142
'''

import connexion
import flask

try:
from decorator import decorator
except ImportError:
import sys
import logging
logging.error('Missing dependency. Please run `pip install decorator`')
sys.exit(1)


def check_auth(username: str, password: str):
'''This function is called to check if a username /
password combination is valid.'''
return username == 'admin' and password == 'secret'


def authenticate():
'''Sends a 401 response that enables basic auth'''
return flask.Response('You have to login with proper credentials', 401,
{'WWW-Authenticate': 'Basic realm="Login Required"'})


@decorator
def requires_auth(f: callable, *args, **kwargs):
auth = flask.request.authorization
if not auth or not check_auth(auth.username, auth.password):
return authenticate()
return f(*args, **kwargs)


@requires_auth
def get_secret() -> str:
return 'This is a very secret string requiring authentication!'


if __name__ == '__main__':
app = connexion.FlaskApp(__name__)
app.add_api('openapi.yaml')
app.run(port=8080)
23 changes: 23 additions & 0 deletions examples/openapi3/basicauth/openapi.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
openapi: 3.0.0
info:
title: Basic Auth Example
version: '1.0'
paths:
/secret:
get:
summary: Return secret string
operationId: app.get_secret
responses:
'200':
description: secret response
content:
'*/*':
schema:
type: string
security:
- basic: []
components:
securitySchemes:
basic:
type: http
scheme: basic
11 changes: 11 additions & 0 deletions examples/openapi3/helloworld/README.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
===================
Hello World Example
===================

Running:

.. code-block:: bash

$ ./hello.py

Now open your browser and go to http://localhost:9090/v1.0/ui/ to see the Swagger UI.
12 changes: 12 additions & 0 deletions examples/openapi3/helloworld/hello.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
#!/usr/bin/env python3

import connexion


def post_greeting(name: str) -> str:
return 'Hello {name}'.format(name=name)

if __name__ == '__main__':
app = connexion.FlaskApp(__name__, port=9090, specification_dir='openapi/')
app.add_api('helloworld-api.yaml', arguments={'title': 'Hello World Example'})
app.run()
30 changes: 30 additions & 0 deletions examples/openapi3/helloworld/openapi/helloworld-api.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
openapi: "3.0.0"

info:
title: Hello World
version: "1.0"
servers:
- url: http://localhost:9090/v1.0

paths:
/greeting/{name}:
post:
summary: Generate greeting
description: Generates a greeting message.
operationId: hello.post_greeting
responses:
200:
description: greeting response
content:
text/plain:
schema:
type: string
example: "hello dave!"
parameters:
- name: name
in: path
description: Name of the person to greet.
required: true
schema:
type: string
example: "dave"
11 changes: 11 additions & 0 deletions examples/openapi3/restyresolver/README.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
=====================
RestyResolver Example
=====================

Running:

.. code-block:: bash

$ ./resty.py

Now open your browser and go to http://localhost:9090/v1.0/ui/ to see the Swagger UI.
1 change: 1 addition & 0 deletions examples/openapi3/restyresolver/api/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
import api.pets # noqa
51 changes: 51 additions & 0 deletions examples/openapi3/restyresolver/api/pets.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import datetime

from connexion import NoContent

pets = {}


def post(body):
name = body.get("name")
tag = body.get("tag")
count = len(pets)
pet = {}
pet['id'] = count + 1
pet["tag"] = tag
pet["name"] = name
pet['last_updated'] = datetime.datetime.now()
pets[pet['id']] = pet
return pet, 201


def put(body):
id = body["id"]
name = body["name"]
tag = body.get("tag")
id = int(id)
pet = pets.get(id, {"id": id})
pet["name"] = name
pet["tag"] = tag
pet['last_updated'] = datetime.datetime.now()
pets[id] = pet
return pets[id]


def delete(id):
id = int(id)
if pets.get(id) is None:
return NoContent, 404
del pets[id]
return NoContent, 204


def get(petId):
id = int(petId)
if pets.get(id) is None:
return NoContent, 404
return pets[id]


def search(limit=100):
# NOTE: we need to wrap it with list for Python 3 as dict_values is not JSON serializable
return list(pets.values())[0:limit]
148 changes: 148 additions & 0 deletions examples/openapi3/restyresolver/resty-api.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
openapi: "3.0.0"
info:
version: 1.0.0
title: Swagger Petstore
license:
name: MIT
servers:
- url: http://localhost:9090/v1.0
paths:
/pets:
get:
summary: List all pets
tags:
- pets
parameters:
- name: limit
in: query
description: How many items to return at one time (max 100)
required: false
schema:
type: integer
format: int32
responses:
'200':
description: An paged array of pets
headers:
x-next:
description: A link to the next page of responses
schema:
type: string
content:
application/json:
schema:
$ref: "#/components/schemas/Pets"
default:
description: unexpected error
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
post:
summary: Create a pet
tags:
- pets
requestBody:
description: Pet to add to the system
content:
application/json:
schema:
$ref: "#/components/schemas/Pet"
responses:
'201':
description: Null response
default:
description: unexpected error
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
put:
summary: Update a pet
tags:
- pets
requestBody:
description: Pet to add to the system
content:
application/json:
schema:
allOf:
- $ref: "#/components/schemas/Pet"
- type: object
required:
- id
properties:
id:
type: integer
format: int64
example:
id: 1
name: chester
tag: sleepy
responses:
'201':
description: Null response
default:
description: unexpected error
content:
application/json:
schema:
$ref: "#/components/schemas/Error"


/pets/{petId}:
get:
summary: Info for a specific pet
tags:
- pets
parameters:
- name: petId
in: path
required: true
description: The id of the pet to retrieve
schema:
type: string
responses:
'200':
description: Expected response to a valid request
content:
application/json:
schema:
$ref: "#/components/schemas/Pets"
default:
description: unexpected error
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
components:
schemas:
Pet:
required:
- name
properties:
id:
readOnly: true
type: integer
format: int64
name:
type: string
tag:
type: string
example:
name: chester
tag: fluffy
Pets:
type: array
items:
$ref: "#/components/schemas/Pet"
Error:
required:
- code
- message
properties:
code:
type: integer
format: int32
message:
type: string
14 changes: 14 additions & 0 deletions examples/openapi3/restyresolver/resty.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
#!/usr/bin/env python
import logging

import connexion
from connexion.resolver import RestyResolver

logging.basicConfig(level=logging.INFO)

if __name__ == '__main__':
app = connexion.FlaskApp(__name__)
app.add_api('resty-api.yaml',
arguments={'title': 'RestyResolver Example'},
resolver=RestyResolver('api'))
app.run(port=9090)
15 changes: 15 additions & 0 deletions examples/openapi3/sqlalchemy/README.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
==================
SQLAlchemy Example
==================

A simple example of how one might use SQLAlchemy as a backing store for a
Connexion based application.

Running:

.. code-block:: bash

$ sudo pip3 install -r requirements.txt
$ ./app.py

Now open your browser and go to http://localhost:8080/ui/ to see the Swagger UI.
Loading