Library for accessing Swagger-enabled APIs
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Core functionality for creating and managing Swagger clients from OpenAPI specifications. This module provides the main entry point to bravado through the SwaggerClient class, which dynamically generates API methods from OpenAPI/Swagger specifications.
The main client class that provides an interface for making API calls based on a Swagger spec. It dynamically creates resource objects and operations from the specification.
class SwaggerClient:
def __init__(self, swagger_spec, also_return_response: bool = False): ...
@classmethod
def from_url(cls, spec_url: str, http_client=None, request_headers: dict = None, config: dict = None) -> 'SwaggerClient': ...
@classmethod
def from_spec(cls, spec_dict: dict, origin_url: str = None, http_client=None, config: dict = None) -> 'SwaggerClient': ...
def get_model(self, model_name: str): ...
def is_equal(self, other: 'SwaggerClient') -> bool: ...
def __deepcopy__(self, memo=None) -> 'SwaggerClient': ...
def __repr__(self) -> str: ...Parameters:
swagger_spec: bravado_core.spec.Spec object containing the parsed OpenAPI specificationalso_return_response (bool): If True, operations return both result and response metadataspec_url (str): URL pointing to the OpenAPI specificationhttp_client: HTTP client instance (defaults to RequestsClient)request_headers (dict): Headers to include with HTTP requestsconfig (dict): Configuration dictionary for bravado and bravado_corespec_dict (dict): OpenAPI specification as a dictionaryorigin_url (str): Base URL for resolving relative referencesmodel_name (str): Name of the model to retrieveReturns:
from_url/from_spec: SwaggerClient instanceget_model: Model class for the specified model nameis_equal: Boolean indicating if clients are equivalentUsage Example:
from bravado.client import SwaggerClient
# Create client from URL
client = SwaggerClient.from_url('http://petstore.swagger.io/v2/swagger.json')
# Access API resources dynamically
pet_store = client.pet
pet = pet_store.getPetById(petId=1).response().result
# Create client from spec dict
import requests
spec_dict = requests.get('http://petstore.swagger.io/v2/swagger.json').json()
client = SwaggerClient.from_spec(spec_dict)
# Get model definitions
Pet = client.get_model('Pet')
new_pet = Pet(name='Fluffy', photoUrls=['http://example.com/fluffy.jpg'])Wraps bravado_core.Resource objects to provide dynamic operation access with consistent response handling.
class ResourceDecorator:
def __init__(self, resource, also_return_response: bool = False): ...Parameters:
resource: bravado_core.resource.Resource objectalso_return_response (bool): Whether to return response metadataMakes operations callable and provides dynamic docstrings. Handles parameter validation, request construction, and returns HttpFuture objects.
class CallableOperation:
def __init__(self, operation, also_return_response: bool = False): ...
def __call__(self, **op_kwargs) -> HttpFuture: ...Parameters:
operation: bravado_core.operation.Operation objectalso_return_response (bool): Whether to return response metadata**op_kwargs: Operation parameters as defined in the OpenAPI specReturns:
Usage Example:
# Operations are called with parameters matching the OpenAPI spec
future = client.pet.getPetById(petId=42)
# Get the response (blocks until complete)
response = future.response()
pet_data = response.result
status_code = response.metadata.status_codeHelper functions for request construction and parameter handling.
def inject_headers_for_remote_refs(request_callable, request_headers: dict): ...
def construct_request(operation, request_options: dict, **op_kwargs) -> dict: ...
def construct_params(operation, request: dict, op_kwargs: dict): ...Parameters:
request_callable: Function that makes HTTP requestsrequest_headers (dict): Headers to inject for remote reference requestsoperation: bravado_core.operation.Operation objectrequest_options (dict): HTTP request configurationrequest (dict): Request dictionary being constructedop_kwargs (dict): Operation parametersReturns:
inject_headers_for_remote_refs: Modified request callable with injected headersconstruct_request: Complete request dictionary ready for HTTP clientconstruct_params: Validated and marshalled parametersClient behavior can be customized through the config parameter:
config = {
'also_return_response': True, # Return response metadata with results
'validate_requests': True, # Validate request parameters
'validate_responses': True, # Validate response data
'use_models': True, # Use model objects for complex types
}
client = SwaggerClient.from_url(spec_url, config=config)SwaggerClient operations can raise various exceptions:
from bravado.exception import HTTPNotFound, BravadoTimeoutError
try:
pet = client.pet.getPetById(petId=999).response().result
except HTTPNotFound:
print("Pet not found")
except BravadoTimeoutError:
print("Request timed out")Install with Tessl CLI
npx tessl i tessl/pypi-bravado