OpenAPI 3 Specification Client and Validator

1.8.2 · active · verified Thu Apr 16

openapi3 is a Python library designed to act as both a client and validator for OpenAPI 3 Specifications. It allows developers to load OpenAPI specification files (YAML or JSON), parse them into Python objects, validate the specification's structure, and interact with the described API by calling defined operations. The library aims to provide an interactive client experience, handling authentication and parameter passing. The current version is 1.8.2, and releases are made as features are developed and bugs are fixed, though a strict cadence isn't published. The project's roadmap indicates ongoing development for richer model and parameter handling.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to load an OpenAPI 3.0 specification from a string (or file), initialize the `OpenAPI` client, call an unauthenticated operation, and then authenticate to call a secured operation. It uses `PyYAML` to parse the YAML spec and `os.environ.get` for securely handling API tokens.

import os
import yaml
from openapi3 import OpenAPI

# Example OpenAPI 3.0 Specification (simplified for demonstration)
# In a real scenario, load this from a file or URL.
spec_content = """
openapi: 3.0.0
info:
  title: Example API
  version: 1.0.0
paths:
  /regions:
    get:
      operationId: getRegions
      summary: Get available regions
      responses:
        '200':
          description: A list of regions
          content:
            application/json:
              schema:
                type: array
                items:
                  type: string
  /secure-data:
    get:
      operationId: getSecureData
      summary: Get secure data
      security:
        - personalAccessToken: []
      responses:
        '200':
          description: Secure data
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: string
components:
  securitySchemes:
    personalAccessToken:
      type: http
      scheme: bearer
      bearerFormat: JWT
"""

# Load the spec (e.g., from a string, or a file)
spec = yaml.safe_load(spec_content)

# Parse the spec into a Python object
api = OpenAPI(spec)

# Call an operation that does not require authentication
try:
    regions = api.call_getRegions()
    print(f"Available regions: {regions}")
except Exception as e:
    print(f"Error calling getRegions: {e}")

# Authenticate for operations that require it
my_token = os.environ.get('API_BEARER_TOKEN', 'YOUR_SUPER_SECRET_TOKEN')
if my_token == 'YOUR_SUPER_SECRET_TOKEN':
    print("Warning: Please set the API_BEARER_TOKEN environment variable for authentication.")

# Note: The `authenticate` method expects the security scheme name and the credentials.
# For 'http' 'bearer', it typically expects the token string directly.
# The example in docs uses `api.authenticate('personalAccessToken', my_token)` for a bearer token.
# However, the exact usage might depend on how the spec defines the security scheme
# and how the `openapi3` library interprets it.
# As per the library's docs, `api.authenticate('personalAccessToken', my_token)` is correct for bearer.

if my_token:
    try:
        api.authenticate('personalAccessToken', my_token)
        secure_data = api.call_getSecureData()
        print(f"Secure data: {secure_data}")
    except Exception as e:
        print(f"Error calling getSecureData: {e}")
else:
    print("Skipping authenticated call as API_BEARER_TOKEN is not set.")

view raw JSON →