Skip to main content

Pyramid plugin for openapi spec generation

Project description

pyramid_apispec

pyramid_apispec allows you to create an OpenAPI specification file using apispec and an online OpenAPI explorer using the Swagger UI project for your Pyramid application and its marshmallow schemas.

Installation

pip install pyramid_apispec

Basic usage

Check out the demo folder and minimal application example by running:

pip install -e '.[demo]'
python demo/app.py

You can then visit your API explorer page at http://0.0.0.0:6543/api-explorer.

Or visit generated documentation here for an example of the demo site. (please note that actual REST API is not working in GitHub pages)

Note: The demo site is using OpenAPI/Swagger v2.0. OpenAPI 3.0 is supported as well, it just uses a different YAML schema so pay attention to examples online.

Example

This example is based on apispec, adapted for Pyramid and pyramid_apispec (updated as of apispec v5.1.0).

This example is using OpenAPI 3.0.2

Hinting a route and its view:

Add the OpenAPI YAML to the view docstring. Optionally use Marshmallow schemas to define the inputs and outputs.

import uuid

from marshmallow import Schema, fields
from pyramid.view import view_config

# Optional marshmallow support
class CategorySchema(Schema):
    id = fields.Int()
    name = fields.Str(required=True)

class PetSchema(Schema):
    categories = fields.List(fields.Nested(CategorySchema))
    name = fields.Str()

@view_config(route_name="random_pet", renderer="json")
def random_pet(request):
    """A cute furry animal endpoint.
    ---
    get:
      description: Get a random pet
      security:
        - ApiKeyAuth: []
      responses:
        200:
          description: Return a pet
          content:
            application/json:
              schema: PetSchema
    """
    # Hardcoded example data
    pet_data = {
        "name": "sample_pet_" + str(uuid.uuid1()),
        "categories": [{"id": 1, "name": "sample_category"}],
    }
    return PetSchema().dump(pet_data)

For more details on how to document the API, see the OpenAPI specification.

Rendering the spec as JSON response:

from apispec import APISpec
from apispec.ext.marshmallow import MarshmallowPlugin
from pyramid.view import view_config
from pyramid_apispec.helpers import add_pyramid_paths

@view_config(route_name="openapi_spec", renderer="json")
def api_spec(request):
    """View to generate the OpenAPI JSON output."""
    spec = APISpec(
        title="Some API",
        version="1.0.0",
        openapi_version="3.0.2",
        plugins=[MarshmallowPlugin()],
    )

    # Optional security scheme support
    api_key_scheme = {"type": "apiKey", "in": "header", "name": "X-API-Key"}
    spec.components.security_scheme("ApiKeyAuth", api_key_scheme)

    # Optionally register Marshmallow schema for more flexibility
    spec.components.schema("Pet", schema=PetSchema)

    # inspect the `random_pet` route and generate operations from docstring
    add_pyramid_paths(spec, 'random_pet', request=request)

    return spec.to_dict()

Adding the API Explorer View

To complement the specification file generation, this package can also provide an API explorer for your application's API via the Swagger UI project:

config.include("pyramid_apispec.views")
config.add_route("openapi_spec", "/openapi.json")
config.pyramid_apispec_add_explorer(spec_route_name="openapi_spec")

By default you need to pass the route name of the view that serves the OpenAPI specification in your application. If needed you can specify a Pyramid permission or custom callable (script_generator argument) to override the default JavaScript configuration of Swagger UI.

The default URL for the explorer is /api-explorer. This setting is controlled via the explorer_route_path argument - the route is registered as pyramid_apispec.api_explorer_path.

Running tests

pip install -e '.[dev]'
tox

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pyramid_apispec-0.5.0.tar.gz (11.6 kB view details)

Uploaded Source

Built Distribution

pyramid_apispec-0.5.0-py2.py3-none-any.whl (10.9 kB view details)

Uploaded Python 2 Python 3

File details

Details for the file pyramid_apispec-0.5.0.tar.gz.

File metadata

  • Download URL: pyramid_apispec-0.5.0.tar.gz
  • Upload date:
  • Size: 11.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.2 importlib_metadata/4.8.1 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.9.7

File hashes

Hashes for pyramid_apispec-0.5.0.tar.gz
Algorithm Hash digest
SHA256 e5e63ccd9a4db2ff76cea5c1014947f5d218ff89df487d3458d7477f5ba85255
MD5 2448227915aecfefcfeaf7c9b92857f5
BLAKE2b-256 a78d8a48ad8ddb056d365602df00ecf4aad75ea543c1ca029254214f1ee2ee4b

See more details on using hashes here.

File details

Details for the file pyramid_apispec-0.5.0-py2.py3-none-any.whl.

File metadata

  • Download URL: pyramid_apispec-0.5.0-py2.py3-none-any.whl
  • Upload date:
  • Size: 10.9 kB
  • Tags: Python 2, Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.2 importlib_metadata/4.8.1 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.9.7

File hashes

Hashes for pyramid_apispec-0.5.0-py2.py3-none-any.whl
Algorithm Hash digest
SHA256 9b73a32e2ebbcf3669b4443a771643e7a80a0b74eb788f5f4b338f569d2010a2
MD5 13f22759a6beee47048a6edf21ad0b44
BLAKE2b-256 2cc9863154341a819dd9ddc7a12d91eb5b2e5a343f81211877962a1f68b353a5

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page