CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-bravado

Library for accessing Swagger-enabled APIs

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

client-management.mddocs/

Client Management

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.

Capabilities

SwaggerClient

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 specification
  • also_return_response (bool): If True, operations return both result and response metadata
  • spec_url (str): URL pointing to the OpenAPI specification
  • http_client: HTTP client instance (defaults to RequestsClient)
  • request_headers (dict): Headers to include with HTTP requests
  • config (dict): Configuration dictionary for bravado and bravado_core
  • spec_dict (dict): OpenAPI specification as a dictionary
  • origin_url (str): Base URL for resolving relative references
  • model_name (str): Name of the model to retrieve

Returns:

  • from_url/from_spec: SwaggerClient instance
  • get_model: Model class for the specified model name
  • is_equal: Boolean indicating if clients are equivalent

Usage 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'])

ResourceDecorator

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 object
  • also_return_response (bool): Whether to return response metadata

CallableOperation

Makes 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 object
  • also_return_response (bool): Whether to return response metadata
  • **op_kwargs: Operation parameters as defined in the OpenAPI spec

Returns:

  • HttpFuture object that can be used to get the response

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_code

Utility Functions

Helper 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 requests
  • request_headers (dict): Headers to inject for remote reference requests
  • operation: bravado_core.operation.Operation object
  • request_options (dict): HTTP request configuration
  • request (dict): Request dictionary being constructed
  • op_kwargs (dict): Operation parameters

Returns:

  • inject_headers_for_remote_refs: Modified request callable with injected headers
  • construct_request: Complete request dictionary ready for HTTP client
  • construct_params: Validated and marshalled parameters

Configuration

Client 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)

Error Handling

SwaggerClient operations can raise various exceptions:

  • SwaggerMappingError: Invalid operation parameters or missing required fields
  • HTTPError: HTTP-level errors (4xx, 5xx status codes)
  • BravadoTimeoutError: Request timeouts
  • BravadoConnectionError: Connection failures
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

docs

authentication.md

client-management.md

configuration.md

exception-handling.md

http-clients.md

index.md

response-handling.md

spec-loading.md

testing-utilities.md

tile.json