Pyramid addon for OpenAPI3 validation of requests and responses.

Overview

Validate Pyramid views against an OpenAPI 3.0 document

CircleCI for pyramid_openapi3 (master branch) Test coverage (master branch) Test coverage (master branch) latest version of pyramid_openapi3 on PyPI Supported Python versions License: MIT Built by these great folks! Talk to us in #pyramid on Freenode IRC

Peace of Mind

The reason this package exists is to give you peace of mind when providing a RESTful API. Instead of chasing down preventable bugs and saying sorry to consumers, you can focus on more important things in life.

  • Your API documentation is never out-of-date, since it is generated out of the API document that you write.
  • The documentation comes with try-it-out examples for every endpoint in your API. You don't have to provide (and maintain) curl commands to showcase how your API works. Users can try it themselves, right in their browsers.
  • Your API document is always valid, since your Pyramid app won't even start if the document does not comply with the OpenAPI 3.0 specification.
  • Automatic request payload validation and sanitization. Your views do not require any code for validation and input sanitation. Your view code only deals with business logic. Tons of tests never need to be written since every request, and its payload, is validated against your API document before it reaches your view code.
  • Your API responses always match your API document. Every response from your view is validated against your document and a 500 Internal Server Error is returned if the response does not exactly match what your document says the output of a certain API endpoint should be. This decreases the effects of Hyrum's Law.
  • A single source of truth. Because of the checks outlined above, you can be sure that whatever your API document says is in fact what is going on in reality. You have a single source of truth to consult when asking an API related question, such as "Remind me again, which fields are returned by the endpoint /user/info?".
  • Based on Pyramid, a mature Python Web framework. Companies such as Mozilla, Yelp, RollBar and SurveyMonkey trust Pyramid, and the new pypi.org runs on Pyramid, too. Pyramid is thoroughly tested and documented, providing flexibility, performance, and a large ecosystem of high-quality add-ons.

Building Robust APIs

Features

Getting started

  1. Declare pyramid_openapi3 as a dependency in your Pyramid project.

  2. Include the following lines:

config.include("pyramid_openapi3")
config.pyramid_openapi3_spec('openapi.yaml', route='/api/v1/openapi.yaml')
config.pyramid_openapi3_add_explorer(route='/api/v1/')
  1. Use the openapi view predicate to enable request/response validation:
@view_config(route_name="foobar", openapi=True, renderer='json')
def myview(request):
    return request.openapi_validated.parameters

For requests, request.openapi_validated is available with two fields: parameters and body. For responses, if the payload does not match the API document, an exception is raised.

Advanced configuration

Relative File References in Spec

A feature introduced in OpenAPI3 is the ability to use $ref links to external files (https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#referenceObject).

To use this, you must ensure that you have all of your spec files in a given directory (ensure that you do not have any code in this directory as all the files in it are exposed as static files), then replace the pyramid_openapi3_spec call that you did in Getting Started with the following:

config.pyramid_openapi3_spec_directory('path/to/openapi.yaml', route='/api/v1/spec')

Some notes:

  • Do not set the route of your pyramid_openapi3_spec_directory to the same value as the route of pyramid_openapi3_add_explorer.
  • The route that you set for pyramid_openapi3_spec_directory should not contain any file extensions, as this becomes the root for all of the files in your specified filepath.
  • You cannot use pyramid_openapi3_spec_directory and pyramid_openapi3_spec in the same app.

Endpoints / Request / Response Validation

Provided with pyramid_openapi3 are a few validation features:

  • incoming request validation (i.e., what a client sends to your app)
  • outgoing response validation (i.e., what your app sends to a client)
  • endpoint validation (i.e., your app registers routes for all defined API endpoints)

These features are enabled as a default, but you can disable them if you need to:

config.registry.settings["pyramid_openapi3.enable_endpoint_validation"] = False
config.registry.settings["pyramid_openapi3.enable_request_validation"] = False
config.registry.settings["pyramid_openapi3.enable_response_validation"] = False

Warning: Disabling request validation will result in request.openapi_validated no longer being available to use.

Register Pyramid's Routes

You can register routes in your pyramid application. First, write the x-pyramid-route-name extension in the PathItem of the OpenAPI schema.

paths:
  /foo:
    x-pyramid-route-name: foo_route
    get:
      responses:
        200:
          description: GET foo

Then put the config directive pyramid_openapi3_register_routes in the app_factory of your application.

config.pyramid_openapi3_register_routes()

This means is equals to

config.add_route("foo_route", pattern="/foo")

Demo / Examples

There are three examples provided with this package:

Both examples come with tests that exhibit pyramid_openapi's error handling and validation capabilities.

A fully built-out app, with 100% test coverage, providing a RealWorld.io API is available at niteoweb/pyramid-realworld-example-app. It is a Heroku-deployable Pyramid app that provides an API for a Medium.com-like social app. You are encouraged to use it as a scaffold for your next project.

Design defense

The authors of pyramid_openapi3 believe that the approach of validating a manually-written API document is superior to the approach of generating the API document from Python code. Here are the reasons:

  1. Both generation and validation against a document are lossy processes. The underlying libraries running the generation/validation will always have something missing. Either a feature from the latest OpenAPI specification, or an implementation bug. Having to fork the underlying library in order to generate the part of your API document that might only be needed for the frontend is unfortunate.

    Validation on the other hand allows one to skip parts of validation that are not supported yet, and not block a team from shipping the document.

  2. The validation approach does sacrifice DRY-ness, and one has to write the API document and then the (view) code in Pyramid. It feels a bit redundant at first. However, this provides a clear separation between the intent and the implementation.

  3. The generation approach has the drawback of having to write Python code even for parts of the API document that the Pyramid backend does not handle, as it might be handled by a different system, or be specific only to documentation or only to the client side of the API. This bloats your Pyramid codebase with code that does not belong there.

Running tests

You need to have pipenv and Python 3.7, 3.8, or 3.9 installed on your machine. Then you can run:

$ make tests

Related packages

These packages tackle the same problem-space:

  • pyramid_oas3 seems to do things very similarly to pyramid_openapi3, but the documentation is not in English and we sadly can't fully understand what it does by just reading the code.
  • pyramid_swagger does a similar thing, but for Swagger 2.0 documents.
  • connexion takes the same "write spec first, code second" approach as pyramid_openapi3, but is based on Flask.
  • bottle-swagger takes the same "write spec first, code second" approach too, but is based on Bottle.
  • pyramid_apispec uses generation with help of apispec and the marshmallow validation library. See above why we prefer validation instead of generation.

Deprecation policy

We do our best to follow the rules below.

  • Support the latest few releases of Python, currently Python 3.7, 3.8, and 3.9.
  • Support the latest few releases of Pyramid, currently 1.10.7 through 2.0.
  • Support the latest few releases of openapi-core, currently 0.13.4 through 0.13.8.
  • See Pipfile.lock for a frozen-in-time known-good-set of all dependencies.

Use in the wild

A couple of projects that use pyramid_openapi3 in production:

Owner
Pylons Project
The Pylons Project is composed of a disparate group of project leaders with experience going back to the very start of Python web frameworks.
Pylons Project
ManiSkill-Learn is a framework for training agents on SAPIEN Open-Source Manipulation Skill Challenge (ManiSkill Challenge), a large-scale learning-from-demonstrations benchmark for object manipulation.

ManiSkill-Learn ManiSkill-Learn is a framework for training agents on SAPIEN Open-Source Manipulation Skill Challenge, a large-scale learning-from-dem

Hao Su's Lab, UCSD 48 Dec 30, 2022
RoboDesk A Multi-Task Reinforcement Learning Benchmark

RoboDesk A Multi-Task Reinforcement Learning Benchmark If you find this open source release useful, please reference in your paper: @misc{kannan2021ro

Google Research 66 Oct 07, 2022
CausaLM: Causal Model Explanation Through Counterfactual Language Models

CausaLM: Causal Model Explanation Through Counterfactual Language Models Authors: Amir Feder, Nadav Oved, Uri Shalit, Roi Reichart Abstract: Understan

Amir Feder 39 Jul 10, 2022
Motion and Shape Capture from Sparse Markers

MoSh++ This repository contains the official chumpy implementation of mocap body solver used for AMASS: AMASS: Archive of Motion Capture as Surface Sh

Nima Ghorbani 135 Dec 23, 2022
Submission to Twitter's algorithmic bias bounty challenge

Twitter Ethics Challenge: Pixel Perfect Submission to Twitter's algorithmic bias bounty challenge, by Travis Hoppe (@metasemantic). Abstract We build

Travis Hoppe 4 Aug 19, 2022
Repo for EchoVPR: Echo State Networks for Visual Place Recognition

EchoVPR Repo for EchoVPR: Echo State Networks for Visual Place Recognition Currently under development Dirs: data: pre-collected hidden representation

Anil Ozdemir 4 Oct 04, 2022
A Tensorflow implementation of BicycleGAN.

BicycleGAN implementation in Tensorflow As part of the implementation series of Joseph Lim's group at USC, our motivation is to accelerate (or sometim

Cognitive Learning for Vision and Robotics (CLVR) lab @ USC 97 Dec 02, 2022
Pytorch implementation of PTNet for high-resolution and longitudinal infant MRI synthesis

Pyramid Transformer Net (PTNet) Project | Paper Pytorch implementation of PTNet for high-resolution and longitudinal infant MRI synthesis. PTNet: A Hi

Xuzhe Johnny Zhang 6 Jun 08, 2022
OptNet: Differentiable Optimization as a Layer in Neural Networks

OptNet: Differentiable Optimization as a Layer in Neural Networks This repository is by Brandon Amos and J. Zico Kolter and contains the PyTorch sourc

CMU Locus Lab 428 Dec 24, 2022
Official implementation of NeurIPS'21: Implicit SVD for Graph Representation Learning

isvd Official implementation of NeurIPS'21: Implicit SVD for Graph Representation Learning If you find this code useful, you may cite us as: @inprocee

Sami Abu-El-Haija 16 Jan 08, 2023
🐸STT integration examples

🐸 STT 0.9.x Examples These are various examples on how to use or integrate 🐸 STT using our packages. It is a good way to just try out 🐸 STT before

coqui 92 Dec 19, 2022
Official implementation of the paper "Lightweight Deep CNN for Natural Image Matting via Similarity Preserving Knowledge Distillation"

Lightweight-Deep-CNN-for-Natural-Image-Matting-via-Similarity-Preserving-Knowledge-Distillation Introduction Accepted at IEEE Signal Processing Letter

DongGeun-Yoon 19 Jun 07, 2022
Human pose estimation from video plays a critical role in various applications such as quantifying physical exercises, sign language recognition, and full-body gesture control.

Pose Detection Project Description: Human pose estimation from video plays a critical role in various applications such as quantifying physical exerci

Hassan Shahzad 2 Jan 17, 2022
Code repository for the work "Multi-Domain Incremental Learning for Semantic Segmentation", accepted at WACV 2022

Multi-Domain Incremental Learning for Semantic Segmentation This is the Pytorch implementation of our work "Multi-Domain Incremental Learning for Sema

Pgxo20 24 Jan 02, 2023
The datasets and code of ACL 2021 paper "Aspect-Category-Opinion-Sentiment Quadruple Extraction with Implicit Aspects and Opinions".

Aspect-Category-Opinion-Sentiment (ACOS) Quadruple Extraction This repo contains the data sets and source code of our paper: Aspect-Category-Opinion-S

NUSTM 144 Jan 02, 2023
Some simple programs built in Python: webcam with cv2 that detects eyes and face, with grayscale filter

Programas en Python Algunos programas simples creados en Python: 📹 Webcam con c

Madirex 1 Feb 15, 2022
TensorFlow implementation of Barlow Twins (Barlow Twins: Self-Supervised Learning via Redundancy Reduction)

Barlow-Twins-TF This repository implements Barlow Twins (Barlow Twins: Self-Supervised Learning via Redundancy Reduction) in TensorFlow and demonstrat

Sayak Paul 36 Sep 14, 2022
This is a Keras implementation of a CNN for estimating age, gender and mask from a camera.

face-detector-age-gender This is a Keras implementation of a CNN for estimating age, gender and mask from a camera. Before run face detector app, expr

Devdreamsolution 2 Dec 04, 2021
The source code of "SIDE: Center-based Stereo 3D Detector with Structure-aware Instance Depth Estimation", accepted to WACV 2022.

SIDE: Center-based Stereo 3D Detector with Structure-aware Instance Depth Estimation The source code of our work "SIDE: Center-based Stereo 3D Detecto

10 Dec 18, 2022
Video lie detector using xgboost - A video lie detector using OpenFace and xgboost

video_lie_detector_using_xgboost a video lie detector using OpenFace and xgboost

2 Jan 11, 2022