Package: pyramid-openapi3
ValidatePyramidviews against anOpenAPI 3.0documentPeace of MindThe 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.YourAPI documentation is never out-of-date, since it is generated out of the API document that you write.The documentation comes withtry-it-outexamplesfor every endpoint in your API. You don't have to provide (and maintain)curlcommands to showcase how your API works. Users can try it themselves, right in their browsers.YourAPI 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 requestpayload 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 APIresponses always match your API document. Every response from your view is validated against your document and a500 Internal Server Erroris 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 ofHyrum'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 onPyramid, amature Python Web framework. Companies such as Mozilla, Yelp, RollBar and SurveyMonkeytrust Pyramid, and the newpypi.orgruns on Pyramid, too. Pyramid is thoroughlytestedanddocumented, providing flexibility, performance, and a large ecosystem ofhigh-quality add-ons.FeaturesValidates your API document (for example,openapi.yamloropenapi.json) against the OpenAPI 3.0 specification using theopenapi-spec-validator.Generates and serves theSwagger try-it-out documentationfor your API.Validates incoming requestsandoutgoing responses against your API document usingopenapi-core.Getting startedDeclarepyramid_openapi3as a dependency in your Pyramid project.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/')Use theopenapiview predicateto enable request/response validation:@view_config(route_name="foobar",openapi=True,renderer='json')defmyview(request):returnrequest.openapi_validated.parametersFor requests,request.openapi_validatedis available with two fields:parametersandbody.
For responses, if the payload does not match the API document, an exception is raised.Advanced configurationRelative File References in SpecA feature introduced in OpenAPI3 is the ability to use$reflinks to external files (https://github.com/OAI/OpenAPI-Specification/blob/main/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), thenreplacethepyramid_openapi3_speccall that you did inGetting Startedwith the following:config.pyramid_openapi3_spec_directory('path/to/openapi.yaml',route='/api/v1/spec')Some notes:Do not set therouteof yourpyramid_openapi3_spec_directoryto the same value as therouteofpyramid_openapi3_add_explorer.Theroutethat you set forpyramid_openapi3_spec_directoryshould not contain any file extensions, as this becomes the root for all of the files in your specifiedfilepath.You cannot usepyramid_openapi3_spec_directoryandpyramid_openapi3_specin the same app.Endpoints / Request / Response ValidationProvided withpyramid_openapi3are 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"]=Falseconfig.registry.settings["pyramid_openapi3.enable_request_validation"]=Falseconfig.registry.settings["pyramid_openapi3.enable_response_validation"]=FalseWarning:Disabling request validation will result inrequest.openapi_validatedno longer being available to use.Register Pyramid's RoutesYou can register routes in your pyramid application.
First, write thex-pyramid-route-nameextension in the PathItem of the OpenAPI schema.paths:/foo:x-pyramid-route-name:foo_routeget:responses:200:description:GET fooThen put the config directivepyramid_openapi3_register_routesin the app_factory of your application.config.pyramid_openapi3_register_routes()This is equal to manually writing the following:config.add_route("foo_route",pattern="/foo")Thepyramid_openapi3_register_routes()method supports setting a factory and route prefix as well. See the source for details.Demo / ExamplesThere are three examples provided with this package:A fairly simplesingle-file app providing a Hello World API.A slightly morebuilt-out app providing a TODO app API.Another TODO app API, defined using aYAML spec split into multiple files.All examples come with tests that exhibit pyramid_openapi's error handling and validation capabilities.Afully built-out app, with 100% test coverage, providing aRealWorld.ioAPI is available atniteoweb/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 defenseThe 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: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.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.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 testsYou need to havepoetryand Python 3.7 through 3.11 installed on your machine.Alternatively, if you usenix, runnix-shellto drop into a shell that has everything prepared for development.Then you can run:maketestsRelated packagesThese packages tackle the same problem-space:pyramid_oas3seems 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_swaggerdoes a similar
thing, but for Swagger 2.0 documents.connexiontakes the same "write spec first, code second" approach as pyramid_openapi3, but is based on Flask.bottle-swaggertakes the same "write spec first, code second" approach too, but is based on Bottle.pyramid_apispecuses generation with
help of apispec and the marshmallow validation library. See abovewhy we prefer validation instead of generation.Deprecation policyWe do our best to follow the rules below.Support the latest few releases of Python, currently Python 3.7 through 3.11.Support the latest few releases of Pyramid, currently 1.10.7 through 2.0.Support the latest few releases ofopenapi-core, currently 0.16.1 through 0.16.2.Seepoetry.lockfor a frozen-in-time known-good-set of all dependencies.Use in the wildA couple of projects that use pyramid_openapi3 in production:WooCart API- User control panel for WooCart Managed WooCommerce service.Kafkai API- User control panel for Kafkai text generation service.Open on-chain data API- Decentralised exchange and blockchain trading data open APIPareto Security Team Dashboard API- Team Dashboard for Pareto Security macOS security app