### Quick Start - Load Swagger API and Initialize Client Source: https://github.com/pyopenapi/pyswagger/blob/develop/README.md Demonstrates basic initialization of pyswagger by loading a Swagger document from a URL, setting up API key and OAuth2 authentication, and creating a client instance. This example shows the minimal setup required to start making authenticated requests to a Swagger-enabled REST API. ```python from pyswagger import App, Security from pyswagger.contrib.client.requests import Client from pyswagger.utils import jp_compose # load Swagger resource file into App object app = App._create_('http://petstore.swagger.io/v2/swagger.json') auth = Security(app) auth.update_with('api_key', '12312312312312312313q') # api key auth.update_with('petstore_auth', '12334546556521123fsfss') # oauth2 # init swagger client client = Client(auth) # a dict is enough for representing a Model in Swagger pet_Tom=dict(id=1, name='Tom', photoUrls=['http://test']) ``` -------------------------------- ### Setup PySwagger Development Environment Source: https://github.com/pyopenapi/pyswagger/blob/develop/README.md Installs development dependencies required for PySwagger contribution and testing. Prepares the environment for running unit tests and submitting pull requests. ```bash pip install -r requirement-dev.txt ``` -------------------------------- ### Install PySwagger Optional Dependencies Source: https://github.com/pyopenapi/pyswagger/blob/develop/README.md Installation commands for optional backend dependencies required for specific use cases: requests for remote/local web servers, tornado for local tornado servers, and flask for native flask app client. ```bash pip install requests ``` ```bash pip install tornado ``` ```bash pip install flask ``` -------------------------------- ### Install PySwagger with pip Source: https://github.com/pyopenapi/pyswagger/blob/develop/README.md Basic installation command for PySwagger package using pip. Additional optional dependencies can be installed separately depending on backend requirements (requests, tornado, flask). ```bash pip install pyswagger ``` -------------------------------- ### Initialize Pyswagger App with Remote Swagger URL Source: https://github.com/pyopenapi/pyswagger/blob/develop/docs/md/tutorial/init.md Demonstrates how to create a pyswagger.App object by providing a remote Swagger resource file URL. This is the primary method for initializing the application with an API definition from a web source. No external dependencies are required beyond the pyswagger library itself. ```python from pyswagger import App # utilize App.create app = App.create('http://petstore.swagger.io/v2/swagger.json') ``` -------------------------------- ### Test Local API Server with PySwagger and Requests Source: https://github.com/pyopenapi/pyswagger/blob/develop/docs/md/tutorial/local.md This snippet shows how to initialize PySwagger with a local Swagger resource file and use the 'requests' client to patch the URL, directing requests to a local server (e.g., localhost:8001). It requires the 'requests' library to be installed. ```python from pyswagger import App from pyswagger.contrib.client.request import Client # create a App with a local resource file app = App.create('/path/to/your/resource/file/swagger.json') # init the client client = Client() # try to making a request client.request( app.op['getUserByName'](username='Tom'), opt=dict( url_netloc='localhost:8001' # patch the url of petstore to localhost:8001 )) ``` -------------------------------- ### Initialize Pyswagger App with Local Swagger File Path Source: https://github.com/pyopenapi/pyswagger/blob/develop/docs/md/tutorial/init.md Shows how to initialize a pyswagger.App object using local file paths for the Swagger resource definition. This includes various formats like file URIs, absolute paths, and directory paths where 'swagger.json' is assumed. Ensure the file or directory exists at the specified location. ```python from pyswagger import App # file URI app = App.create('file:///home/workspace/local/swagger.json') # with hostname app = App.create('file://localhost/home/workspace/local/swagger.json') # absolute path app = App.create('/home/workspace/local/swagger.json') # without the file name, because 'swagger.json' is a predefined name app = App.create('/home/workspace/local') ``` -------------------------------- ### Load Single OpenAPI Spec from Memory Dictionary with DictGetter Source: https://github.com/pyopenapi/pyswagger/blob/develop/docs/md/ref/resolver.md Creates a pyswagger.App instance using an in-memory dictionary specification (such as a petstore example) via DictGetter and custom Resolver. The getter is initialized with an empty string path and a dictionary mapping containing the loaded spec, then passed to App.load() with a Resolver instance. ```python from pyswagger import App from pyswagger.resolve import Resolver from pyswagger.getter import DictGetter loaded_spec # the loaded spec in memory as dict # prepare the getter getter = DictGetter([''], {'': loaded_spec}) app = App.load('', resolver=Resolver(default_getter=getter)) app.prepare() ``` -------------------------------- ### Load Swagger App with Custom MIME Codec in Python Source: https://github.com/pyopenapi/pyswagger/blob/develop/docs/md/tutorial/mime.md Demonstrates loading a Swagger specification with a custom MIME codec. The App.load() method accepts a mime_codec parameter to enable custom serialization for specific MIME types. This example loads the Petstore API and prepares it in strict mode. ```python from pyswagger import App _mime_codec = _create_mime_codec() app = App.load('http://petstore.swagger.io/v2/swagger.json', mime_codec=_mime_codec) app.prepare(strict=True) ``` -------------------------------- ### Test Flask Applications with PySwagger Test Client Source: https://context7.com/pyopenapi/pyswagger/llms.txt Integrate PySwagger with Flask's test client to directly test Flask applications without the need to start an HTTP server. This facilitates efficient and isolated testing of API endpoints defined in a Flask app. ```python from flask import Flask, jsonify from pyswagger import App from pyswagger.contrib.client.flask import Client # Your Flask application flask_app = Flask(__name__) @flask_app.route('/api/users/') def get_user(user_id): return jsonify({'id': user_id, 'name': 'John Doe'}) # Load swagger spec and test swagger_app = App._create_('file:///path/to/swagger.json') client = Client(backend=flask_app) # Make test requests without HTTP server resp = client.request(swagger_app.op['getUser'](userId=1)) assert resp.status == 200 assert resp.data.name == 'John Doe' ``` -------------------------------- ### Query API with Date Range Parameters using pyswagger Source: https://context7.com/pyopenapi/pyswagger/llms.txt Illustrates how to query an API for events within a specific date range. It constructs start and end dates using `datetime` and `timedelta`, extracts the date part, and passes them as parameters to the API operation. ```python from datetime import datetime, timedelta # Assuming 'app' and 'client' are initialized pyswagger objects # start_date = datetime.now() - timedelta(days=7) # end_date = datetime.now() # req, resp = app.op['getEventsBetweenDates']( # startDate=start_date.date(), # endDate=end_date.date() # ) # response = client.request((req, resp)) # Placeholder for actual request/response objects class MockEvent: def __init__(self, title, event_date): self.title = title self.event_date = event_date class MockResponseDataList(list): pass class MockResponseWithList: def __init__(self): self.data = MockResponseDataList([ MockEvent('Past Event', datetime(2023, 1, 1).date()), MockEvent('Recent Event', datetime.now().date()) ]) response = MockResponseWithList() # Simulate iterating through response data for event in response.data: print(f"{event.title} on {event.event_date}") ``` -------------------------------- ### Initialize App, Security, and Client in Python Source: https://github.com/pyopenapi/pyswagger/blob/develop/docs/rst/index.rst Demonstrates how to load a Swagger resource file into an App object, initialize Security for various authorization types (basic, API key, OAuth2), and create a Client instance for making API requests. It shows how to configure authentication credentials. ```python from pyswagger import App, Security from pyswagger.contrib.client.requests import Client # load Swagger resource file into App object app = App._create_('http://petstore.swagger.wordnik.com/api/api-docs') # init Security for authorization auth = Security(app) auth.update_with('simple_basic_auth', ('user', 'password')) # basic auth auth.update_with('simple_api_key', '12312312312312312313q') # api key auth.update_with('simple_oauth2', '12334546556521123fsfss') # oauth2 # init swagger client client = Client(auth) ``` -------------------------------- ### Execute API Request with Client - Python Source: https://github.com/pyopenapi/pyswagger/blob/develop/docs/rst/topics/main.rst Demonstrate the complete workflow of creating an App, initializing Security, instantiating a Client, obtaining Request/Response objects from operations, executing requests, and retrieving response data. Shows the relationship between App, Security, and Client components. ```python app = App._create_('http://petstore.swagger.wordnik.com/api/api-docs') auth = Security(app) client = Client(auth) # get Request and Response from Swagger.op req, resp = app.op['getPetById'](Id=1) # call request resp = client.request((req, resp)) # get data back assert resp.data.id == 1 ``` -------------------------------- ### Initialize Security and Configure Authorizations - Python Source: https://github.com/pyopenapi/pyswagger/blob/develop/docs/rst/topics/main.rst Set up Security component with an App instance and configure multiple authorization schemes including Basic Authentication, API Key, and OAuth2 tokens. Security acts as a placeholder for authorizations and is passed to clients for automatic authorization application. ```python # must be initialized with App auth = Security(app) # insert autorization information app.update_with('simple_basicAuth', ('user', 'password')) app.update_with('simple_apiKey', 'token123') app.update_with('simple_oath2', 'token123456') # pass into a client client = TornadoClient(auth) # authorization would be applied automatically client.request(...) ``` -------------------------------- ### Make API Requests with pyswagger in Python Source: https://github.com/pyopenapi/pyswagger/blob/develop/docs/rst/index.rst Illustrates how to use the pyswagger client to make API requests, including adding a pet and retrieving a pet by its ID. It also shows how to redirect requests to a different host for local testing and how to handle parameters that accept single values or lists. ```python # a request to create a new pet pet_Tom=dict(id=1, name='Tom') # a dict is enough client.request(app.op['addPet'](body=pet_Tom)) # a request to get the pet back pet = client.request(app.op['getPetById'])(petId=1).data assert pet.id == 1 assert pet.name == 'Tom' # redirect all requests targeting 'petstore.swagger.wordnik.com' # to 'localhost:9001' for testing locally client.request( app.op['addPet'](body=pet_Tom), opt={'url_netloc': 'localhost:9001'} ) # allowMultiple parameter client.request(app.op['getPetsByStatus'](status='sold')) # one value client.request(app.op['getPetsByStatus'](status=['available', 'sold'])) # multiple value, wrapped by list. ``` -------------------------------- ### Initialize SwaggerClient and Make a Request Source: https://github.com/pyopenapi/pyswagger/blob/develop/docs/md/ref/client.md Demonstrates initializing the SwaggerClient with optional security and making a request to an API operation. The client abstracts HTTP library differences and handles authorization. ```python from pyswagger import SwaggerClient # Initialize the client, security can be a Security object or None client = SwaggerClient(security=None) # Construct a request for the 'addPet' operation with a dictionary body # The result of app.op['operationId'] is a tuple of (request, response) req, resp = client.app.op['addPet'](body=dict(id=1, name='Tom')) # Make the actual request using the client response = client.request(req, resp) # The 'response' object contains status, data, header, message, and raw data. ``` -------------------------------- ### Create App and Access Operations - Python Source: https://github.com/pyopenapi/pyswagger/blob/develop/docs/rst/topics/main.rst Initialize an App instance with a Swagger API definition URL and access Operation objects using nicknames or resource name plus nickname pairs. The App loads the Swagger definition and provides access to individual API operations through the op property. ```python app = App._create_('http://petstore.swagger.wordnik.com/api/api-docs') assert app.op['getPetsByStatus'] == app.op['pet', 'getPetsByStatus'] # resource name is required when nicknames collid app.op['user', 'getById'] app.op['pet', 'getById'] ``` -------------------------------- ### Dumping PySwagger Object to Dictionary Source: https://github.com/pyopenapi/pyswagger/blob/develop/docs/md/ref/app.md Shows how to serialize the root Swagger or ResourceList object into a Python dictionary using the `App.dump()` method. ```python app = App._create_('http://petstore.swagger.io/v2/swagger.json') # Dump the Swagger object to a dictionary synopsis = app.dump() print(synopsis) ``` -------------------------------- ### Accessing API Operations in PySwagger Source: https://github.com/pyopenapi/pyswagger/blob/develop/docs/md/ref/app.md Demonstrates how to access Operation objects using `App.op` for unique and non-unique API nicknames. It also shows how to use `App.resolve` with JSON pointers for accessing operations, providing an alternative to direct `App.op` access. ```python app = App._create_('http://petstore.swagger.io/v2/swagger.json') # call an API when its nickname is unique app.op['getPetById'] # call an API when its nickname collides with other resources app.op['user', 'getById'] # operationId:'getById', tags:'user' (or a user resource in Swagger 1.2) app.op['pet', 'getById'] # operationId:'getById', tags:'pet' (or a pet resource in Swagger 1.2) # utilize App.resolve to do the same thing app.resolve('#/paths/~1pet~1{petId}').get # instead of writing JSON-pointers by yourselves, utilize pyswagger.utils.jp_compose from pyswagger import utils app.resolve(utils.jp_compose('/pet/{petId}', base='#/paths')).get ``` -------------------------------- ### Run PySwagger Unit Tests with pytest Source: https://github.com/pyopenapi/pyswagger/blob/develop/README.md Executes the PySwagger test suite with verbose output and code coverage reporting. Generates coverage reports configured via .coveragerc file to measure test coverage of the pyswagger package. ```bash python -m pytest -s -v --cov=pyswagger --cov-config=.coveragerc pyswagger/tests ``` -------------------------------- ### Load Swagger 1.2 and Export as JSON/YAML in Python Source: https://github.com/pyopenapi/pyswagger/blob/develop/docs/md/tutorial/converter.md Demonstrates loading a Swagger 1.2 document using pyswagger's App.create() method and exporting it to both JSON and YAML formats. The app.dump() method converts the document to Swagger 2.0 specification. This is useful for migrating legacy API documentation to the newer format. ```python from pyswagger import App import json import yaml # load a document in Swagger 1.2 app = App.create('/path/to/your/resource/file/resource_list.json') # dump root object(Swagger Object) in Swagger 2.0 into a dict obj = app.dump() # save as a JSON file with open('./swagger.json', 'w') as w: w.write(json.dumps(obj, indent=2)) # save as a YAML file with open('./swagger.yaml', 'w') as w: w.write(yaml.dump(obj)) ``` -------------------------------- ### Generate and Send Random API Request with pyswagger Source: https://github.com/pyopenapi/pyswagger/blob/develop/docs/md/tutorial/render.md This snippet shows how to initialize pyswagger, create an App from a local Swagger file, and then use a Renderer to generate random input for an API operation. The generated input is then sent using a requests-based client. Dependencies include 'pyswagger' and 'requests'. ```python from pyswagger import App from pyswagger.primitives import Renderer from pyswagger.contrib.client.requests import Client # create a App with a local resource file app = App.create('/path/to/your/resource/file/swagger.json') # init client client = Client() # init renderer renderer = Renderer() # assume you have an Operation to test input_ = renderer.render_all( app.s('user').post # the Operation ) # this generated input could be passed to Operation.__call__, # to get a pair of (Request, Response), or just # pass them to client resp = client.request(app.s('user').post(**input_)) ``` -------------------------------- ### Unit Testing Flask API with PySwagger Source: https://context7.com/pyopenapi/pyswagger/llms.txt Set up unit tests for Flask-based Swagger API operations using PySwagger's App and Client classes. Demonstrates test fixture initialization with Swagger specification loading and API request/response validation. ```python import unittest class FlaskAPITest(unittest.TestCase): def setUp(self): self.swagger_app = App._create_('file:///path/to/swagger.json') self.client = Client(backend=flask_app) def test_get_user(self): resp = self.client.request( self.swagger_app.op['getUser'](userId=1) ) self.assertEqual(resp.status, 200) self.assertIsNotNone(resp.data.name) ``` -------------------------------- ### Create and Execute Pet API Request using PySwagger Source: https://github.com/pyopenapi/pyswagger/blob/develop/README.md Demonstrates how to create a new pet resource and retrieve it using PySwagger's operation-based API. Shows accessing Operation objects via App.op with operationId, executing requests with client.request(), and processing JSON responses with assertions. ```python # a request to create a new pet client.request(app.op['addPet'](body=pet_Tom)) # - access an Operation object via App.op when operationId is defined # - a request to get the pet back req, resp = app.op['getPetById'](petId=1) # prefer json as response req.produce('application/json') pet = client.request((req, resp)).data assert pet.id == 1 assert pet.name == 'Tom' # new ways to get Operation object corresponding to 'getPetById'. # 'jp_compose' stands for JSON-Pointer composition req, resp = app.resolve(jp_compose('/pet/{petId}', base='#/paths')).get(petId=1) req.produce('application/json') pet = client.request((req, resp)).data assert pet.id == 1 ``` -------------------------------- ### Resolving JSON References in PySwagger Source: https://github.com/pyopenapi/pyswagger/blob/develop/docs/md/ref/app.md Demonstrates how to use `App.resolve` to access objects within a Swagger definition using JSON References. This includes accessing local definitions and external documents by providing a URL. ```python app = App._create_('http://petstore.swagger.io/v2/swagger.json') # Access a local schema definition user_schema = app.resolve('#/definitions/User') # Access a schema definition from an external document external_user_schema = app.resolve('http://another_site.com/apis/swagger.json#/definitions/User') ``` -------------------------------- ### Making API Requests with PySwagger Source: https://context7.com/pyopenapi/pyswagger/llms.txt Demonstrates how to create and send various types of API requests using PySwagger, including JSON responses, JSON bodies, XML responses, and form data submissions. It shows how to set content types and accept headers. ```python from pyswagger import App from pyswagger.contrib.client.requests import Client # Assume app and client are initialized # app = App._create_('your_swagger.json') # client = Client() # Request JSON response # req, resp = app.op['getUser'](userId=1) # req.produce('application/json') # Sets Accept header # response = client.request((req, resp)) # Send JSON body # req, resp = app.op['createUser'](body={'name': 'John', 'email': 'john@example.com'}) # req.consume('application/json') # Sets Content-Type header # req.produce('application/json') # response = client.request((req, resp)) # Request XML response # req, resp = app.op['getReport'](reportId=5) # req.produce('application/xml') # response = client.request((req, resp)) # Send form data # req, resp = app.op['submitForm']( # formData={'field1': 'value1', 'field2': 'value2'} # ) # req.consume('application/x-www-form-urlencoded') # response = client.request((req, resp)) ``` -------------------------------- ### Load Multi-Document OpenAPI Spec from Memory with DictGetter Source: https://github.com/pyopenapi/pyswagger/blob/develop/docs/md/ref/resolver.md Configures DictGetter for multi-document specifications (e.g., Swagger 1.2 or Swagger 2.0 with external $ref documents) by passing all document paths/URLs in the correct order as the first parameter and mapping each path to its corresponding loaded dictionary object. ```python from pyswagger import App from pyswagger.resolve import Resolver from pyswagger.getter import DictGetter # those loaded object in memory loaded_resource_list loaded_pet loaded_user loaded_store # prepare the getter, the loaded order should be past in 1st parameter as list getter = DictGetter([ '', 'pet.json', 'user.json', 'store.json', ], { '': loaded_resource_list, 'pet.json': loaded_pet, 'store.json': loaded_store, 'user.json': loaded_user }) app = App.load('', resolver=Resolver(default_getter=getter)) app.prepare() ``` -------------------------------- ### Dump and Inspect Swagger Specification with pyswagger Source: https://context7.com/pyopenapi/pyswagger/llms.txt Shows how to load a Swagger specification (v1.2) using pyswagger, convert it to v2.0 format, and then dump it as a Python dictionary. It demonstrates accessing different parts of the specification like version, info, paths, and definitions. ```python from pyswagger import App import json # Load Swagger 1.2 spec (automatically converted to 2.0) # app = App._create_('http://api.example.com/swagger-1.2.json') # Mock App object for demonstration class MockApp: def __init__(self): self.version = '1.2' self.root = MockRoot() class MockRoot: def __init__(self): self.swagger = '2.0' self.info = {'title': 'Mock API'} self.paths = {'/items': {}} self.definitions = {'Item': {'properties': {'name': {}}}} app = MockApp() # Dump as dictionary (in 2.0 format) # swagger_dict = app.dump() # Mock dump method def mock_dump(): return { "swagger": "2.0", "info": {"title": "Mock API Title"}, "paths": {"/mock/path": {}}, "definitions": {"MockModel": {"properties": {"field1": {}}}} } app.dump = mock_dump swagger_dict = app.dump() print(f"Swagger version: {swagger_dict['swagger']}") print(f"API title: {swagger_dict['info']['title']}") print(f"Paths: {list(swagger_dict['paths'].keys())}") # Save to file # with open('converted-swagger-2.0.json', 'w') as f: # json.dump(swagger_dict, f, indent=2) # Access specific parts definitions = swagger_dict.get('definitions', {}) for model_name, model_schema in definitions.items(): print(f"Model: {model_name}") print(f" Properties: {list(model_schema.get('properties', {}).keys())}") # Compare original vs processed # print(f"Original version: {app.version}") # '1.2' # print(f"Root object version: {app.root.swagger}") # '2.0' # Mocking original version access for demonstration print(f"Original version: {app.version}") print(f"Root object version: {app.root.swagger}") ``` -------------------------------- ### Configure API Authentication in Python with pyswagger Source: https://context7.com/pyopenapi/pyswagger/llms.txt Set up authentication mechanisms like API Key, Basic Auth, or OAuth2 using pyswagger's Security class. The configured security object can then be passed to the HTTP client for authenticated requests. ```python from pyswagger import App, Security from pyswagger.contrib.client.requests import Client app = App._create_('http://petstore.swagger.io/v2/swagger.json') auth = Security(app) # API Key authentication (in header or query) auth.update_with('api_key', '12345678abcdefgh') # Basic authentication auth.update_with('basic_auth', ('username', 'password')) # OAuth2 authentication auth.update_with('petstore_auth', 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...') # Use authenticated client client = Client(auth) req, resp = app.op['getUserProfile']() response = client.request((req, resp)) print(response.data.username) ``` -------------------------------- ### Uploading Files with PySwagger Source: https://context7.com/pyopenapi/pyswagger/llms.txt Illustrates how to handle file uploads using PySwagger's multipart/form-data request capabilities. It covers uploading a single file with metadata and form fields, and also uploading a file where the data is read directly from the filename. ```python from pyswagger import App from pyswagger.contrib.client.requests import Client app = App._create_('http://petstore.swagger.io/v2/swagger.json') client = Client() # Upload single file with open('/path/to/image.jpg', 'rb') as f: file_obj = { 'filename': 'pet_photo.jpg', 'data': f, 'header': { 'Content-Type': 'image/jpeg', 'Content-Transfer-Encoding': 'binary' } } req, resp = app.op['uploadFile']( petId=123, file=file_obj, additionalMetadata='Pet profile photo' ) response = client.request((req, resp)) print(response.data.message) # Upload without explicit data (reads from filename) file_obj = { 'filename': '/path/to/document.pdf', 'data': None, # Will read from filename 'header': {'Content-Type': 'application/pdf'} } req, resp = app.op['uploadDocument'](file=file_obj) response = client.request((req, resp)) ``` -------------------------------- ### Load and Initialize Swagger Application in Python Source: https://context7.com/pyopenapi/pyswagger/llms.txt Instantiate a pyswagger App object from a Swagger specification URL or local file path. This object can then be used to access API metadata and operations. Supports loading with validation enabled or disabled. ```python from pyswagger import App # Load from remote URL app = App._create_('http://petstore.swagger.io/v2/swagger.json') # Load from local file app = App._create_('file:///path/to/swagger.json') # Load with validation disabled app = App._create_('http://api.example.com/swagger.json', strict=False) # Access API metadata print(app.version) # '2.0' print(app.schemes) # ['http', 'https'] print(app.root.info.title) # 'Petstore API' ``` -------------------------------- ### Accessing Operations via JSON Pointers with PySwagger Source: https://context7.com/pyopenapi/pyswagger/llms.txt Shows different methods to access API operations using PySwagger, including composing JSON pointers, direct resolution with shortcuts, resolving by operationId, and resolving by tag and operationId. It also demonstrates accessing all operations on a given path. ```python from pyswagger import App from pyswagger.utils import jp_compose app = App._create_('http://petstore.swagger.io/v2/swagger.json') # Method 1: Compose JSON pointer for path json_pointer = jp_compose('/pet/{petId}', base='#/paths') # Returns: '#/paths/~1pet~1{petId}' path_item = app.resolve(json_pointer) operation = path_item.get # Access GET operation req, resp = operation(petId=1) # Method 2: Direct resolution with shortcut operation = app.s('/pet/{petId}').get req, resp = operation(petId=1) # Method 3: Resolve by operationId operation = app.op['getPetById'] req, resp = operation(petId=1) # Method 4: Resolve by tag and operationId operation = app.op['pet', 'getPetById'] req, resp = operation(petId=1) # Access all operations on a path path_item = app.s('/pet') print(path_item.post) # POST operation print(path_item.put) # PUT operation ``` -------------------------------- ### Configure SSL Verification and Request Options Source: https://context7.com/pyopenapi/pyswagger/llms.txt Manage SSL verification, set timeouts, and configure other request options for production deployments. Options like disabling SSL verification (for development only) or specifying a custom certificate can be passed via `send_opt`. ```python from pyswagger import App from pyswagger.contrib.client.requests import Client app = App._create_('https://api.example.com/swagger.json') # Disable SSL verification (development only) client = Client(send_opt={'verify': False}) response = client.request(app.op['getUsers']()) # Custom SSL certificate client = Client(send_opt={'verify': '/path/to/certfile.pem'}) response = client.request(app.op['getUsers']()) # Set timeout client = Client(send_opt={'timeout': 30}) response = client.request(app.op['getLargeDataset']()) # Combine multiple options client = Client(send_opt={ 'verify': True, 'timeout': 60, 'allow_redirects': True, 'stream': False }) # Use with authentication from pyswagger import Security auth = Security(app) auth.update_with('api_key', 'key123') client = Client(auth=auth, send_opt={'verify': True, 'timeout': 30}) response = client.request(app.op['secureEndpoint']()) ``` -------------------------------- ### Configure PySwagger Logging for Debugging Source: https://github.com/pyopenapi/pyswagger/blob/develop/README.md Sets up Python logging for PySwagger to output debug-level messages to console. Useful for troubleshooting issues by capturing detailed logging output with timestamp, logger name, log level, and message format. ```python import logging logger = logging.getLogger('pyswagger') formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') console = logging.StreamHandler() console.setLevel(logging.DEBUG) console.setFormatter(formatter) logger.addHandler(console) logger.setLevel(logging.DEBUG) ... your stuff ``` -------------------------------- ### Validating Swagger Specifications with PySwagger Source: https://context7.com/pyopenapi/pyswagger/llms.txt Demonstrates how to validate Swagger specifications using PySwagger. It covers validation during app creation with the 'strict' flag, manual validation, and accessing basic API information like version, schemes, and base path. ```python from pyswagger import App # Validate during load (raises exception on error) try: app = App._create_('http://api.example.com/swagger.json', strict=True) print("Swagger spec is valid") except Exception as e: print(f"Validation failed: {e}") # Manual validation without exceptions app = App._create_('http://api.example.com/swagger.json', strict=False) errors = app.validate(strict=False) if errors: print(f"Found {len(errors)} validation errors:") for location, error_type, message in errors: print(f" Location: {location}") print(f" Type: {error_type}") print(f" Message: {message}") print() else: print("No validation errors found") # Check specific parts print(f"API version: {app.version}") print(f"Schemes: {app.schemes}") print(f"Base path: {app.root.basePath}") ``` -------------------------------- ### Validating Swagger API Definitions in PySwagger Source: https://github.com/pyopenapi/pyswagger/blob/develop/docs/md/ref/app.md Explains how to validate a loaded Swagger API definition using `App.validate`. When `strict=True`, it raises an exception on failure and returns validation errors as a list of tuples. ```python app = App._create_('http://petstore.swagger.io/v2/swagger.json') # Validate with strict mode enabled try: app.validate(strict=True) except Exception as e: print(f"Validation failed: {e}") # Get validation errors without raising exception errors = app.validate() for error in errors: print(f"Error: {error}") ``` -------------------------------- ### Handle Query Parameters and Arrays in Python with pyswagger Source: https://context7.com/pyopenapi/pyswagger/llms.txt Construct API requests that include query parameters, including support for array parameters with different collection formats like 'multi'. This allows for flexible filtering and pagination of API results. ```python from pyswagger import App from pyswagger.contrib.client.requests import Client app = App._create_('http://petstore.swagger.io/v2/swagger.json') client = Client() # Single query parameters req, resp = app.op['findPetsByStatus'](status='available') response = client.request((req, resp)) # Multiple query parameters req, resp = app.op['findPets']( status='available', limit=10, offset=0 ) response = client.request((req, resp)) # Array query parameters (collectionFormat: multi) req, resp = app.op['findPetsByTags'](tags=['dog', 'friendly', 'small']) response = client.request((req, resp)) # Iterate through results for pet in response.data: print(f"Pet: {pet.name}, Status: {pet.status}") ``` -------------------------------- ### Use Async Tornado Client for High Concurrency Source: https://context7.com/pyopenapi/pyswagger/llms.txt Leverage the `TornadoClient` for making asynchronous API requests, suitable for high-concurrency applications. This allows for efficient handling of multiple requests concurrently using Tornado's event loop. ```python from tornado import gen, ioloop from pyswagger import App from pyswagger.contrib.client.tornado import TornadoClient app = App._create_('http://api.example.com/swagger.json') client = TornadoClient() @gen.coroutine def fetch_user_data(): # Single async request resp = yield client.request(app.op['getUser'](userId=1)) print(f"User: {resp.data.name}") raise gen.Return(resp.data) @gen.coroutine def fetch_multiple_users(): # Parallel async requests user_ids = [1, 2, 3, 4, 5] requests = [ client.request(app.op['getUser'](userId=uid)) for uid in user_ids ] responses = yield requests users = [resp.data for resp in responses] for user in users: print(f"Fetched user: {user.name}") raise gen.Return(users) # Run async operations ioloop.IOLoop.current().run_sync(fetch_user_data) ioloop.IOLoop.current().run_sync(fetch_multiple_users) ``` -------------------------------- ### Test API Against Local Servers with URL Overrides Source: https://context7.com/pyopenapi/pyswagger/llms.txt Override URL components like host, port, and scheme to direct API requests to local development servers or different environments. This is crucial for testing against instances not exposed publicly. ```python from pyswagger import App from pyswagger.contrib.client.requests import Client from pyswagger.io import Request app = App._create_('http://api.example.com/swagger.json') client = Client() # Override host and scheme for local testing req, resp = app.op['getUsers']() response = client.request( (req, resp), opt={ Request.opt_url_netloc: 'localhost:8080', Request.opt_url_scheme: 'http' } ) # Test different environments staging_response = client.request( app.op['getUser'](userId=1), opt={ Request.opt_url_netloc: 'staging.example.com', Request.opt_url_scheme: 'https' } ) dev_response = client.request( app.op['getUser'](userId=1), opt={ Request.opt_url_netloc: 'dev.local:3000', Request.opt_url_scheme: 'http' } ) print(f"Local: {response.status}") print(f"Staging: {staging_response.status}") print(f"Dev: {dev_response.status}") ``` -------------------------------- ### Handle External References in Swagger Documents Source: https://context7.com/pyopenapi/pyswagger/llms.txt Automatically resolve external $ref references across multiple Swagger documents using PySwagger's resolver. Supports custom URL loading hooks for redirecting requests between environments like production and staging. ```python from pyswagger import App # Load spec with external references # swagger.json contains: {"$ref": "http://api.example.com/models.json#/definitions/User"} app = App._create_('http://api.example.com/swagger.json') # External references are automatically resolved user_schema = app.resolve('http://api.example.com/models.json#/definitions/User') print(user_schema.type) # 'object' print(user_schema.properties.keys()) # Use in operations req, resp = app.op['createUser'](body={ 'username': 'john_doe', 'email': 'john@example.com' }) # Access externally defined models external_model = app.resolve('#/definitions/ExternalModel') print(external_model.required) # Custom URL loading hook for testing def redirect_hook(url): if 'production.com' in url: return url.replace('production.com', 'staging.com') return url from pyswagger.resolve import Resolver resolver = Resolver(url_load_hook=redirect_hook) app = App._create_( 'http://production.com/swagger.json', resolver=resolver ) ``` -------------------------------- ### Access API Response Status, Data, Raw, and Headers with pyswagger and requests Source: https://github.com/pyopenapi/pyswagger/blob/develop/docs/md/tutorial/response.md This Python snippet shows how to make an API request using pyswagger with the requests client and then access various parts of the response. It covers checking the HTTP status code, accessing parsed JSON data based on a schema, retrieving the raw response string, and inspecting HTTP headers. It also demonstrates how to disable automatic body parsing and handle the raw body manually. ```python from pyswagger import App from pyswagger.contrib.client.requests import Client app = App.create('/path/to/your/resource/file/swagger.json') client = Client() # making a request resp = client.request(app.op['getUserByName'](username='Tom')) # Status assert resp.status == 200 # Data # it should return a data accord with '#/definitions/User' Schema object assert resp.data.id == 1 assert resp.data.username == 'Tom' # Raw assert resp.raw == '{"id": 1, "username": "Tom"}' # To disable parsing of body parameter, and handle 'raw' on your own. resp.raw_body_only = True assert resp.data == None # Header # header is a dict, its values are lists of values, # because keys in HTTP header allow duplication. # # when the input header is: # A: 1, # A: 2, # B, 1 assert sorted(resp.header['A']) == [1, 2] assert resp.header['B'] == [1] ``` -------------------------------- ### Add Custom Headers to pyswagger Client Requests Source: https://github.com/pyopenapi/pyswagger/blob/develop/docs/md/tutorial/customized_headers.md Shows how to add custom headers to API requests using pyswagger's Client.request() method. Supports single header values, multiple values per header key, and optional header value concatenation. Requires pyswagger and requests libraries with an initialized App instance. ```python from pyswagger import App from pyswagger.contrib.client.requests import Client app = App.create('http://petstore.swagger.io/v2/swagger.json') client = Client() # provide a header client.request( app.op['getUserByName'](username='Tom'), headers={'MY-TEST-HEADER': '123'} ) # headers with multiple value to one key client.request( app.op['getUserByName'](username='Tom'), headers=[('MY-TEST-HEADER', '123'), ('MY-TEST-HEADER', '456')] ) # headers with multiple value to one key, and join them by comma client.request( app.op['getUserByName'](username='Tom'), headers=[('MY-TEST-HEADER', '123'), ('MY-TEST-HEADER', '456')], opt={'join_headers': True} ) ``` -------------------------------- ### Send and Parse Dates/Datetimes with pyswagger Source: https://context7.com/pyopenapi/pyswagger/llms.txt Demonstrates sending date and datetime objects in API requests and parsing them from responses. It handles automatic formatting for 'date' and 'date-time' types and shows how to access and format datetime objects from the response. ```python from datetime import date, datetime # Assuming 'app' and 'client' are initialized pyswagger objects # req, resp = app.op['createEvent']( # body={ # 'title': 'Team Meeting', # 'event_date': date(2025, 12, 25), # Format: date # 'start_time': datetime(2025, 12, 25, 14, 0), # Format: date-time # 'end_time': datetime(2025, 12, 25, 15, 30), # 'created_at': datetime.now() # } # ) # response = client.request((req, resp)) # Placeholder for actual request/response objects class MockResponseData: def __init__(self): self.event_date = date(2025, 12, 25) self.start_time = datetime(2025, 12, 25, 14, 0) self.created_at = datetime.now() self.title = 'Mock Event' class MockResponse: def __init__(self): self.data = MockResponseData() response = MockResponse() # Parse date/datetime from response event = response.data print(event.event_date) # datetime.date object print(event.start_time) # datetime.datetime object print(event.created_at.strftime('%Y-%m-%d %H:%M:%S')) ``` -------------------------------- ### Patching Request Body for Invalid Input Testing (Python) Source: https://github.com/pyopenapi/pyswagger/blob/develop/docs/md/tutorial/invalid.md This snippet demonstrates how to use pyswagger to send an API request with intentionally invalid data. It shows how to create an App instance, a Client, prepare a request with invalid data, and then patch the 'body' parameter of the request object before sending it. This is useful for testing how a server handles malformed requests. ```python from pyswagger import App from pyswagger.contrib.client.requests import Client app = App._create_('http://petstore.swagger.io/v2/swagger.json') client = Client() pet_tom = dict( id=123, name='Tom', photoUrls='https://github.com/', status='available') req, resp = app.op['addPet'](body=pet_tom) # patching the "body" parameter named "body", ... which seems cumbersome req._p['body']['body']['id'] = 'not_valid' resp = client.request((req, resp,)) print resp.status ``` -------------------------------- ### Render API Request with Fixed Parameters using Templates Source: https://github.com/pyopenapi/pyswagger/blob/develop/docs/md/tutorial/render.md This snippet demonstrates using templates with pyswagger's Renderer to fix specific properties or parameters when generating random API request inputs. It shows how to update 'object_template' for schema properties and 'parameter_template' for operation parameters. Dependencies include 'pyswagger' and 'requests'. ```python # assume you have 'email', 'password' to post a comment renderer = Renderer() opt = renderer.default() # post a random blog with login info # -------- # assume this Operation takes one body parameter, # and the parameter corresponding to a Schema, # with 'email', 'password', 'blog' properties... op = app.s('blog').post opt['object_template'].update({ 'email': test_email, 'password': test_password }) client.request(op(renderer.render_all(op, opt=opt))) # update phone number of a user # -------- # assume this Operation takes three query parameters: 'email', 'passwprd', and a random phone number... op = app.s('user').update opt['parameter_template'].update({ 'email': test_email, 'password': test_password }) client.request(op(renderer.render_all(op, opt=opt))) ``` -------------------------------- ### Accessing Model Definitions and Schemas with PySwagger Source: https://context7.com/pyopenapi/pyswagger/llms.txt Explains how to retrieve and inspect Swagger model definitions and schemas using PySwagger. It covers accessing models by name, inspecting their properties, accessing nested definitions via JSON pointer, and checking enum values for properties. ```python from pyswagger import App app = App._create_('http://petstore.swagger.io/v2/swagger.json') # Access model by name pet_schema = app.m['Pet'] print(pet_schema.type) # 'object' print(pet_schema.required) # ['name', 'photoUrls'] # Inspect properties for prop_name, prop_schema in pet_schema.properties.items(): print(f"{prop_name}: {prop_schema.type}") # id: integer # name: string # status: string # photoUrls: array # Access nested definitions via JSON pointer user_schema = app.resolve('#/definitions/User') print(user_schema.properties['username'].type) # 'string' # Check enum values status_prop = pet_schema.properties['status'] if status_prop.enum: print(status_prop.enum) # ['available', 'pending', 'sold'] ``` -------------------------------- ### Custom Getter for Restricted Service Loading in PySwagger Source: https://github.com/pyopenapi/pyswagger/blob/develop/docs/md/tutorial/restricted_service.md This Python code defines a custom getter function 'my_load' to fetch OpenAPI specifications from restricted services. It uses the 'requests' library to handle authentication headers and returns the service response text. This approach is necessary when the default getter cannot access the service. ```python from pyswagger.getter import SimpleGetter # use any library you like, for example, the beautiful 'requests' library import requests def my_load(url): # prepare your auth info your_header_with_auth_info = {...} # make a request resp = requests.post('xxx', headers=your_header_with_auth_info, verify=False) if resp.statuc_code is 200: # return the raw string return resp.text else: raise Exception('something not ok') ``` -------------------------------- ### Constructing a File Upload Parameter for Swagger Source: https://github.com/pyopenapi/pyswagger/blob/develop/docs/md/ref/client.md Shows how to define a file object for multipart/form-data uploads according to RFC2388. This includes specifying content type, transfer encoding, filename, and the file data itself. ```python YouFile = { # header values used in multipart/form-data according to RFC2388 'header': { 'Content-Type': 'text/plain', # according to RFC2388, available values are '7bit', '8bit', 'binary' 'Content-Transfer-Encoding': 'binary' }, 'filename': 'a.txt', 'data': None # or any file-like object } ``` -------------------------------- ### Create Custom XML MIME Codec in Python Source: https://github.com/pyopenapi/pyswagger/blob/develop/docs/md/tutorial/mime.md Defines a custom XmlCodec class that implements marshal and unmarshal methods for XML serialization. The marshal method converts Python dictionaries to XML using dicttoxml, while unmarshal parses XML data back to dictionaries using xmltodict. This codec can be registered with MimeCodec to handle application/xml and text/xml MIME types. ```python from pyswagger.primitives import MimeCodec import xmltodict import dicttoxml class XmlCodec: def marshal(self, value, **kwargs): # name, _type, _format is available in kwargs name = kwargs['name'] if name: return dicttoxml.dicttoxml(value, root=True, custom_root=name, attr_type=False) else: return '' + dicttoxml.dicttoxml(value, root=False, attr_type=False) def unmarshal(self, data, **kwargs): # name, _type, _format is available in kwargs return xmltodict.parse(data) def _create_mime_codec(): mime_codec = MimeCodec() xmlCodec = XmlCodec() for _type in ['application', 'text']: mime_codec.register('%s/xml' % _type, xmlCodec) return mime_codec ``` -------------------------------- ### JSON Schema with Relative File Reference (PySwagger) Source: https://github.com/pyopenapi/pyswagger/blob/develop/CHANGES.md Demonstrates the use of relative file references in JSON schemas within PySwagger, allowing a reference to a 'User' schema located in a different file ('other_folder/User.json'). ```json { "definitions":{ "User": { "$ref": "other_folder/User.json" } } } ```