A pluggable API specification generator. Currently supports the OpenAPI Specification (f.k.a. the Swagger specification)..

Overview

apispec

PyPI version Build status Documentation marshmallow 3 only OpenAPI Specification 2/3 compatible code style: black

A pluggable API specification generator. Currently supports the OpenAPI Specification (f.k.a. the Swagger specification).

Features

  • Supports the OpenAPI Specification (versions 2 and 3)
  • Framework-agnostic
  • Built-in support for marshmallow
  • Utilities for parsing docstrings

Installation

$ pip install -U apispec

When using marshmallow pluging, ensure a compatible marshmallow version is used:

$ pip install -U apispec[marshmallow]

Example Application

from apispec import APISpec
from apispec.ext.marshmallow import MarshmallowPlugin
from apispec_webframeworks.flask import FlaskPlugin
from flask import Flask
from marshmallow import Schema, fields


# Create an APISpec
spec = APISpec(
    title="Swagger Petstore",
    version="1.0.0",
    openapi_version="3.0.2",
    plugins=[FlaskPlugin(), MarshmallowPlugin()],
)

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


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


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


# Optional Flask support
app = Flask(__name__)


@app.route("/random")
def random_pet():
    """A cute furry animal endpoint.
    ---
    get:
      description: Get a random pet
      security:
        - ApiKeyAuth: []
      responses:
        200:
          content:
            application/json:
              schema: PetSchema
    """
    pet = get_random_pet()
    return PetSchema().dump(pet)


# Register the path and the entities within it
with app.test_request_context():
    spec.path(view=random_pet)

Generated OpenAPI Spec

import json

print(json.dumps(spec.to_dict(), indent=2))
# {
#   "paths": {
#     "/random": {
#       "get": {
#         "description": "Get a random pet",
#         "security": [
#           {
#             "ApiKeyAuth": []
#           }
#         ],
#         "responses": {
#           "200": {
#             "content": {
#               "application/json": {
#                 "schema": {
#                   "$ref": "#/components/schemas/Pet"
#                 }
#               }
#             }
#           }
#         }
#       }
#     }
#   },
#   "tags": [],
#   "info": {
#     "title": "Swagger Petstore",
#     "version": "1.0.0"
#   },
#   "openapi": "3.0.2",
#   "components": {
#     "parameters": {},
#     "responses": {},
#     "schemas": {
#       "Category": {
#         "type": "object",
#         "properties": {
#           "name": {
#             "type": "string"
#           },
#           "id": {
#             "type": "integer",
#             "format": "int32"
#           }
#         },
#         "required": [
#           "name"
#         ]
#       },
#       "Pet": {
#         "type": "object",
#         "properties": {
#           "name": {
#             "type": "string"
#           },
#           "category": {
#             "type": "array",
#             "items": {
#               "$ref": "#/components/schemas/Category"
#             }
#           }
#         }
#       }
#       "securitySchemes": {
#          "ApiKeyAuth": {
#            "type": "apiKey",
#            "in": "header",
#            "name": "X-API-Key"
#         }
#       }
#     }
#   }
# }

print(spec.to_yaml())
# components:
#   parameters: {}
#   responses: {}
#   schemas:
#     Category:
#       properties:
#         id: {format: int32, type: integer}
#         name: {type: string}
#       required: [name]
#       type: object
#     Pet:
#       properties:
#         category:
#           items: {$ref: '#/components/schemas/Category'}
#           type: array
#         name: {type: string}
#       type: object
#   securitySchemes:
#     ApiKeyAuth:
#       in: header
#       name: X-API-KEY
#       type: apiKey
# info: {title: Swagger Petstore, version: 1.0.0}
# openapi: 3.0.2
# paths:
#   /random:
#     get:
#       description: Get a random pet
#       responses:
#         200:
#           content:
#             application/json:
#               schema: {$ref: '#/components/schemas/Pet'}
#       security:
#       - ApiKeyAuth: []
# tags: []

Documentation

Documentation is available at https://apispec.readthedocs.io/ .

Ecosystem

A list of apispec-related libraries can be found at the GitHub wiki here:

https://github.com/marshmallow-code/apispec/wiki/Ecosystem

Support apispec

apispec is maintained by a group of volunteers. If you'd like to support the future of the project, please consider contributing to our Open Collective:

Donate to our collective

Professional Support

Professionally-supported apispec is available through the Tidelift Subscription.

Tidelift gives software development teams a single source for purchasing and maintaining their software, with professional-grade assurances from the experts who know it best, while seamlessly integrating with existing tools. [Get professional support]

Get supported apispec with Tidelift

Security Contact Information

To report a security vulnerability, please use the Tidelift security contact. Tidelift will coordinate the fix and disclosure.

Project Links

License

MIT licensed. See the bundled LICENSE file for more details.

Owner
marshmallow-code
Python object serialization and deserialization, lightweight and fluffy
marshmallow-code
LotteryBuyPredictionWebApp - Lottery Purchase Prediction Model

Lottery Purchase Prediction Model Objective and Goal Predict the lottery type th

Wanxuan Zhang 2 Feb 14, 2022
A tool that allows for versioning sites built with mkdocs

mkdocs-versioning mkdocs-versioning is a plugin for mkdocs, a tool designed to create static websites usually for generating project documentation. mk

Zayd Patel 38 Feb 26, 2022
A repository of links with advice related to grad school applications, research, phd etc

A repository of links with advice related to grad school applications, research, phd etc

Shaily Bhatt 946 Dec 30, 2022
Read write method - Read files in various types of formats

一个关于所有格式文件读取的方法 1。 问题描述: 各种各样的文件格式,读写操作非常的麻烦,能够有一种方法,可以整合所有格式的文件,方便用户进行读取和写入。 2

2 Jan 26, 2022
A simple tutorial to get you started with Discord and it's Python API

Hello there Feel free to fork and star, open issues if there are typos or you have a doubt. I decided to make this post because as a newbie I never fo

Sachit 1 Nov 01, 2021
Example Python code for running the mango-explorer marketmaker

🥭 Mango Explorer 📖 Introduction This guide will show you how to load and run a customisable marketmaker that runs on Mango Markets using the mango-e

Blockworks Foundation 2 Apr 11, 2022
🍭 epub generator for lightnovel.us 轻之国度 epub 生成器

lightnovel_epub 本工具用于基于轻之国度网页生成epub小说。 注意:本工具仅作学习交流使用,作者不对内容和使用情况付任何责任! 原理 直接抓取 HTML,然后将其中的图片下载至本地,随后打包成 EPUB。

gyro永不抽风 188 Dec 30, 2022
Python document object mapper (load python object from JSON and vice-versa)

lupin is a Python JSON object mapper lupin is meant to help in serializing python objects to JSON and unserializing JSON data to python objects. Insta

Aurélien Amilin 24 Nov 09, 2022
level2-data-annotation_cv-level2-cv-15 created by GitHub Classroom

[AI Tech 3기 Level2 P Stage] 글자 검출 대회 팀원 소개 김규리_T3016 박정현_T3094 석진혁_T3109 손정균_T3111 이현진_T3174 임종현_T3182 Overview OCR (Optimal Character Recognition) 기술

6 Jun 10, 2022
The blazing-fast Discord bot.

Wavy Wavy is an open-source multipurpose Discord bot built with pycord. Wavy is still in development, so use it at your own risk. Tools and services u

Wavy 7 Dec 27, 2022
Plover jyutping - Plover plugin for Jyutping input

Plover plugin for Jyutping Installation Navigate to the repo directory: cd plove

Samuel Lo 1 Mar 17, 2022
Spin-off Notice: the modules and functions used by our research notebooks have been refactored into another repository

Fecon235 - Notebooks for financial economics. Keywords: Jupyter notebook pandas Federal Reserve FRED Ferbus GDP CPI PCE inflation unemployment wage income debt Case-Shiller housing asset portfolio eq

Adriano 825 Dec 27, 2022
This is a repository for "100 days of code challenge" projects. You can reach all projects from beginner to professional which are written in Python.

100 Days of Code It's a challenge that aims to gain code practice and enhance programming knowledge. Day #1 Create a Band Name Generator It's actually

SelenNB 2 May 12, 2022
A Material Design theme for MkDocs

A Material Design theme for MkDocs Create a branded static site from a set of Markdown files to host the documentation of your Open Source or commerci

Martin Donath 12.3k Jan 04, 2023
Python For Finance Cookbook - Code Repository

Python For Finance Cookbook - Code Repository

Packt 544 Dec 25, 2022
My Sublime Text theme

rsms sublime text theme Install: cd path/to/your/sublime/packages git clone https://github.com/rsms/sublime-theme.git rsms-theme You'll also need the

Rasmus 166 Jan 04, 2023
A tutorial for people to run synthetic data replica's from source healthcare datasets

Synthetic-Data-Replica-for-Healthcare Description What is this? A tailored hands-on tutorial showing how to use Python to create synthetic data replic

11 Mar 22, 2022
Data Inspector is an open-source python library that brings 15++ types of different functions to make EDA, data cleaning easier.

Data Inspector Data Inspector is an open-source python library that brings 15 types of different functions to make EDA, data cleaning easier. Author:

Kazi Amit Hasan 38 Nov 24, 2022
A `:github:` role for Sphinx

sphinx-github-role A github role for Sphinx. Usage Basic usage MyST: :caption: index.md See {github}`astrojuanlu/sphinx-github-role#1`. reStructuredT

Juan Luis Cano Rodríguez 4 Nov 22, 2022
Showing potential issues with merge strategies

Showing potential issues with merge strategies Context There are two branches in this repo: main and a feature branch feat/inverting-method (not the b

Rubén 2 Dec 20, 2021