### Install Connexion and Dependencies Source: https://github.com/spec-first/connexion/blob/main/examples/helloworld_async/README.rst Installs Connexion with support for Swagger UI and Uvicorn, essential for running the example. ```bash python -m venv my-venv source my-venv/bin/activate pip install 'connexion[swagger-ui,uvicorn]>=3.1.0' ``` -------------------------------- ### Install Connexion Source: https://context7.com/spec-first/connexion/llms.txt Install Connexion with optional extras for Flask, Swagger UI, or a development server. ```bash pip install connexion ``` ```bash pip install connexion[flask] ``` ```bash pip install connexion[swagger-ui] ``` ```bash pip install connexion[uvicorn] ``` ```bash pip install connexion[swagger-ui,uvicorn] ``` -------------------------------- ### Run OpenAPI Specification with Mock Server Source: https://github.com/spec-first/connexion/blob/main/docs/cli.md Run a mock server that returns example responses defined in the OpenAPI specification. If no examples are defined, Connexion generates them if installed with the mock extra. ```bash $ connexion run your_api.yaml --mock=all ``` ```bash $ connexion run https://raw.githubusercontent.com/spec-first/connexion/main/examples/helloworld_async/spec/openapi.yaml --mock=all ``` -------------------------------- ### Install Connexion and Dependencies Source: https://github.com/spec-first/connexion/blob/main/examples/jwt/README.rst Create a virtual environment and install the necessary libraries for Connexion with Flask, Swagger UI, and Uvicorn support. Ensure you have the latest version of Connexion (>=3.1.0). ```bash python -m venv my-venv source my-venv/bin/activate pip install 'connexion[flask,swagger-ui,uvicorn]>=3.1.0' pip install -r requirements.txt ``` -------------------------------- ### Install Connexion with Development Dependencies Source: https://github.com/spec-first/connexion/blob/main/README.md Install Connexion using poetry with all extras and set up pre-commit hooks for automatic code formatting and static analysis. ```Shell pip install poetry poetry install --all-extras pre-commit install ``` -------------------------------- ### Install Connexion and Dependencies Source: https://github.com/spec-first/connexion/blob/main/examples/frameworks/README.rst Installs Connexion with swagger-ui and uvicorn support, along with other project requirements. Ensure you are in a virtual environment. ```bash python -m venv my-venv source my-venv/bin/activate pip install 'connexion[swagger-ui,uvicorn]>=3.1.0' pip install -r requirements.txt ``` -------------------------------- ### Customizing the Middleware Stack Source: https://context7.com/spec-first/connexion/llms.txt This example demonstrates how to customize the default middleware stack, for instance, by removing the SecurityMiddleware. ```Python from connexion import AsyncApp, ConnexionMiddleware from connexion.middleware.security import SecurityMiddleware # Remove SecurityMiddleware (e.g., when using API Gateway for auth) middlewares = [ middleware for middleware in ConnexionMiddleware.default_middlewares if middleware is not SecurityMiddleware ] app = AsyncApp(__name__, middlewares=middlewares) app.add_api("openapi.yaml") ``` -------------------------------- ### Start Mock Token Info Server Source: https://github.com/spec-first/connexion/blob/main/examples/oauth2/README.rst Run the mock token info server in the background. This server simulates the token validation process. ```bash python mock_tokeninfo.py & ``` -------------------------------- ### Install Connexion with Flask and Uvicorn Source: https://github.com/spec-first/connexion/blob/main/examples/apikey/README.rst Install the necessary libraries for your virtual environment. Ensure you are using connexion version 3.1.0 or higher. ```bash python -m venv my-venv source my-venv/bin/activate pip install 'connexion[flask,swagger-ui,uvicorn]>=3.1.0' ``` -------------------------------- ### Install Connexion Source: https://github.com/spec-first/connexion/blob/main/docs/quickstart.md Install Connexion using pip. Optional extras can be installed for additional features like Flask compatibility, Swagger UI, or uvicorn support. ```bash pip install connexion ``` ```bash pip install connexion[] pip install connexion[,]. ``` -------------------------------- ### Install Connexion with Dependencies Source: https://github.com/spec-first/connexion/blob/main/examples/reverseproxy/README.rst Install Connexion along with necessary dependencies for Flask, Swagger UI, and uvicorn using pip. ```bash $ pip install 'connexion[flask,swagger-ui,uvicorn]>=3.1.0' ``` -------------------------------- ### Connexion with MethodResolver Source: https://context7.com/spec-first/connexion/llms.txt Example of setting up Connexion with MethodResolver for routing to class methods. ```APIDOC ```python from connexion import FlaskApp from connexion.resolver import MethodResolver app = FlaskApp(__name__) app.add_api("openapi.yaml", resolver=MethodResolver("api")) ``` ``` -------------------------------- ### Connexion with RestyResolver Source: https://context7.com/spec-first/connexion/llms.txt Example of setting up Connexion with RestyResolver for automatic routing based on path and HTTP method. ```APIDOC ```python from connexion import FlaskApp from connexion.resolver import RestyResolver app = FlaskApp(__name__) app.add_api("openapi.yaml", resolver=RestyResolver("api")) # With this resolver, routes are automatically mapped: # GET / -> api.get # GET /pets -> api.pets.search # POST /pets -> api.pets.post # GET /pets/{id} -> api.pets.get # PUT /pets/{id} -> api.pets.put # DELETE /pets/{id} -> api.pets.delete ``` ``` -------------------------------- ### Install Connexion with Pip Source: https://github.com/spec-first/connexion/blob/main/README.md Install the base Connexion package using pip. Optional extras like swagger-ui or uvicorn can be installed separately or together. ```shell $ pip install connexion ``` ```shell $ pip install connexion[swagger-ui] ``` ```shell $ pip install connexion[swagger-ui,uvicorn] ``` -------------------------------- ### Launch Connexion Server Source: https://github.com/spec-first/connexion/blob/main/examples/apikey/README.rst Start the Connexion server by running your Python application file. This command assumes your application is named app.py. ```bash python app.py ``` -------------------------------- ### Deploying Connexion Applications with ASGI Servers Source: https://context7.com/spec-first/connexion/llms.txt Examples of running Connexion applications in production using ASGI servers like uvicorn and gunicorn. Covers basic startup, using uvicorn workers with gunicorn, setting a reverse proxy root path, and enabling SSL/TLS. ```bash # Using uvicorn uvicorn app:app --host 0.0.0.0 --port 8080 --workers 4 ``` ```bash # Using gunicorn with uvicorn workers (recommended for production) gunicorn app:app -k uvicorn.workers.UvicornWorker \ --bind 0.0.0.0:8080 \ --workers 4 \ --timeout 120 ``` ```bash # With reverse proxy root path uvicorn app:app --root-path /api/v1 ``` ```bash # With SSL/TLS uvicorn app:app --ssl-keyfile key.pem --ssl-certfile cert.pem ``` -------------------------------- ### Run Connexion Server with Quart Source: https://github.com/spec-first/connexion/blob/main/examples/frameworks/README.rst Launches the Connexion server using the Quart framework. This command starts the application, making it accessible via your browser. ```bash python hello_quart.py ``` -------------------------------- ### Parameter Name Sanitation Example Source: https://github.com/spec-first/connexion/blob/main/docs/request.md Demonstrates how Connexion sanitizes parameter names by removing invalid characters and ensuring they start with a letter or underscore. ```python >>> re.sub('^[^a-zA-Z_]+', '', re.sub('[^0-9a-zA-Z_]', '', '$top')) 'top' ``` -------------------------------- ### Run Connexion Server with Starlette Source: https://github.com/spec-first/connexion/blob/main/examples/frameworks/README.rst Launches the Connexion server using the Starlette framework. This command starts the application, making it accessible via your browser. ```bash python hello_starlette.py ``` -------------------------------- ### Customize Middleware Stack in AsyncApp Source: https://github.com/spec-first/connexion/blob/main/docs/middleware.md Instantiate AsyncApp with a custom list of middlewares to modify the default stack. This example removes the SecurityMiddleware. ```python from connexion import AsyncApp, ConnexionMiddleware from connexion.middleware.security import SecurityMiddleware middlewares = [middleware for middleware in ConnexionMiddleware.default_middlewares if middleware is not SecurityMiddleware] app = AsyncApp(__name__, middlewares=middlewares) ``` -------------------------------- ### Testing with test_client Source: https://context7.com/spec-first/connexion/llms.txt Use the built-in test client for testing your Connexion application, including GET, POST, and protected endpoints. ```python import pytest from connexion import AsyncApp def create_app(): app = AsyncApp(__name__) app.add_api("openapi.yaml") return app def test_get_pets(): """Test GET /pets endpoint.""" app = create_app() with app.test_client() as client: response = client.get("/api/v1/pets") assert response.status_code == 200 assert isinstance(response.json(), list) def test_create_pet(): """Test POST /pets endpoint.""" app = create_app() with app.test_client() as client: pet_data = {"name": "Fluffy", "animal_type": "cat"} response = client.post( "/api/v1/pets", json=pet_data, headers={"Content-Type": "application/json"} ) assert response.status_code == 201 assert response.json()["name"] == "Fluffy" def test_protected_endpoint_without_auth(): """Test that protected endpoints require authentication.""" app = create_app() with app.test_client() as client: response = client.get("/api/v1/secret") assert response.status_code == 401 def test_protected_endpoint_with_auth(): """Test protected endpoint with valid JWT token.""" app = create_app() with app.test_client() as client: # Get token token_response = client.get("/api/v1/auth/123") token = token_response.text # Access protected resource response = client.get( "/api/v1/secret", headers={"Authorization": f"Bearer {token}"} ) assert response.status_code == 200 ``` -------------------------------- ### Configure Nginx for Path Altering Source: https://github.com/spec-first/connexion/blob/main/examples/reverseproxy/README.rst Example Nginx configuration to proxy requests and set the X-Forwarded-Path header for path alteration. ```nginx location /proxied { proxy_pass http://192.168.0.1:5001; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-Path /proxied; } ``` -------------------------------- ### OpenAPI Specification for Greeting API Source: https://github.com/spec-first/connexion/blob/main/docs/quickstart.md An example OpenAPI 3.0 specification defining a POST endpoint '/greeting/{name}' that links to the 'run.post_greeting' Python function. ```yaml openapi: "3.0.0" info: title: Greeting application version: 0.0.1 paths: /greeting/{name}: post: operationId: run.post_greeting responses: '200': description: "Greeting response" content: text/plain: schema: type: string parameters: - name: name in: path required: true schema: type: string ``` -------------------------------- ### OpenAPI 3 Parameters with Pythonic Conversion Source: https://github.com/spec-first/connexion/blob/main/docs/request.md Example OpenAPI 3 specification demonstrating parameters that will be converted to snake_case when `pythonic_params` is enabled. ```yaml paths: /foo: get: operationId: api.foo_get parameters: - name: filter description: Some filter. in: query schema: type: string required: true - name: FilterOption description: Some filter option. in: query schema: type: string ``` -------------------------------- ### Python Function with Default Body Argument Source: https://github.com/spec-first/connexion/blob/main/docs/request.md Example of a Python function expecting the request body as the 'body' argument. ```python # Default def foo_get(body) ... ``` -------------------------------- ### Enable CORS with ConnexionMiddleware Source: https://github.com/spec-first/connexion/blob/main/docs/cookbook.md Wrap your ASGI app with ConnexionMiddleware and add CORSMiddleware for CORS support. This setup is useful for custom ASGI frameworks. ```python from pathlib import Path from asgi_framework import App from connexion import ConnexionMiddleware from starlette.middleware.cors import CORSMiddleware app = App(__name__) app = ConnexionMiddleware(app) app.add_middleware( CORSMiddleware, position=MiddlewarePosition.BEFORE_EXCEPTION, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) app.add_api("openapi.yaml") if __name__ == "__main__": app.run(f"{Path(__file__).stem}:app", port=8080) ``` -------------------------------- ### API Key Authentication Python Implementation Source: https://context7.com/spec-first/connexion/llms.txt Implements API key authentication by validating tokens against a predefined dictionary and returning user information. This example uses a simple in-memory dictionary for tokens; a database should be used in production. ```python from pathlib import Path import connexion from connexion.exceptions import OAuthProblem # Token database (use a real database in production) TOKEN_DB = { "asdf1234567890": {"uid": 100, "scope": ["read", "write"]}, "qwerty0987654321": {"uid": 200, "scope": ["read"]}, } def apikey_auth(token, required_scopes): """Validate API key and return user info.""" info = TOKEN_DB.get(token) if not info: raise OAuthProblem("Invalid API key") return info def get_secret(user): """Protected endpoint - receives user from auth.""" return {"message": f"Hello user {user}! Here is your secret."} app = connexion.FlaskApp(__name__, specification_dir="spec") app.add_api("openapi.yaml") if __name__ == "__main__": app.run(f"{Path(__file__).stem}:app", port=8080) ``` -------------------------------- ### Custom XML Response Validator Example Source: https://github.com/spec-first/connexion/blob/main/docs/validation.md Demonstrates creating a custom response validator for XML by subclassing AbstractResponseBodyValidator and integrating it into a custom validator map. ```python from connexion.datastructures import MediaTypeDict from connexion.validators import AbstractResponseBodyValidator, TextResponseBodyValidator class MyCustomXMLResponseValidator(AbstractResponseBodyValidator): def _parse(self, stream: t.Generator[bytes, None, None]) -> t.Any: ... def _validate(self, body: dict): ... validator_map = { "response": MediaTypeDict( { "*/*json": JSONResponseBodyValidator, "*/*xml": MyCustomXMLResponseValidator, "text/plain": TextResponseBodyValidator, } ), } ``` -------------------------------- ### Running Connexion 2.X Application (Deprecated) Source: https://github.com/spec-first/connexion/blob/main/docs/v3.md This example shows the deprecated method of running a Connexion 2.X application by accessing the underlying Flask app. It is no longer valid in Connexion 3.0. ```python import connexion app = connexion.App(__name__) flask_app = app.app if __name__ == "__main__": flask_app.run() ``` -------------------------------- ### MethodViewResolver Path Definitions Source: https://github.com/spec-first/connexion/blob/main/docs/routing.md Example OpenAPI YAML defining paths and HTTP methods that would be routed by MethodViewResolver to corresponding methods in a Flask MethodView class. ```yaml paths: /foo: get: # Implied operationId: api.FooView.get post: # Implied operationId: api.FooView.post '/foo/{id}': get: # Implied operationId: api.FooView.get put: # Implied operationId: api.FooView.put copy: # Implied operationId: api.FooView.copy delete: # Implied operationId: api.FooView.delete ``` -------------------------------- ### OpenAPI 3 Path Parameter Definition Source: https://github.com/spec-first/connexion/blob/main/docs/routing.md Example of defining a path parameter 'id' of type integer for the '/users/{id}' path in an OpenAPI 3 specification. ```yaml paths: /users/{id}: parameters: - in: path name: id # Note the name is the same as in the path required: true schema: type: integer description: The user ID ``` -------------------------------- ### Use ConnexionMiddleware with WSGI App Source: https://context7.com/spec-first/connexion/llms.txt Wrap a WSGI application using a2wsgi and then ConnexionMiddleware to add API functionality. Note that the specification directory is not directly passed to ConnexionMiddleware in this WSGI example. ```python from connexion import ConnexionMiddleware from a2wsgi import WSGIMiddleware from flask import Flask flask_app = Flask(__name__) asgi_app = WSGIMiddleware(flask_app) app = ConnexionMiddleware(asgi_app) ``` -------------------------------- ### Create AsyncApp Application Source: https://context7.com/spec-first/connexion/llms.txt Initialize an AsyncApp with a specification directory and register an API. Run the application for development. ```python from pathlib import Path from connexion import AsyncApp # Create the application app = AsyncApp(__name__, specification_dir="spec") # Register an API from OpenAPI specification app.add_api("openapi.yaml") # Run the application (development only) if __name__ == "__main__": app.run(f"{Path(__file__).stem}:app", port=8080) ``` -------------------------------- ### Create AsyncApp Application Source: https://github.com/spec-first/connexion/blob/main/README.md Use AsyncApp for new projects requiring native asynchronous support. It's a lightweight option. ```Python from connexion import AsyncApp app = AsyncApp(__name__) ``` -------------------------------- ### Run Connexion Server Source: https://github.com/spec-first/connexion/blob/main/examples/helloworld_async/README.rst Launches the Connexion server using a Python script. Ensure 'hello.py' contains your application code. ```bash python hello.py ``` -------------------------------- ### Flask MethodView Class Structure Source: https://github.com/spec-first/connexion/blob/main/docs/routing.md Defines a Flask MethodView class named 'PetsView' with methods corresponding to HTTP operations like POST, PUT, DELETE, and GET. The 'get' method handles optional 'petId' and 'limit' parameters. ```python from flask.views import MethodView class PetsView(MethodView): def post(self, body: dict): ... def put(self, petId, body: dict): ... def delete(self, petId): ... def get(self, petId=None, limit=100): ... ``` -------------------------------- ### GET /api/v1/pets/{pet_id} Source: https://context7.com/spec-first/connexion/llms.txt Retrieves a specific pet by its unique ID. ```APIDOC ## GET /api/v1/pets/{pet_id} ### Description Retrieves the details of a specific pet identified by its `pet_id`. ### Method GET ### Endpoint /api/v1/pets/{pet_id} ### Parameters #### Path Parameters - **pet_id** (integer) - Required - The unique identifier of the pet. ### Response #### Success Response (200) - **Pet** (object) - Details of the pet. #### Error Response (404) - Description: Pet not found. ### Response Example ```json { "id": 1, "name": "Buddy", "animal_type": "dog", "created": "2023-10-27T10:00:00Z" } ``` ``` -------------------------------- ### Connexion CLI Help Command Source: https://github.com/spec-first/connexion/blob/main/docs/cli.md Execute this command to view all available options for the `connexion run` command. ```bash $ connexion run --help ``` -------------------------------- ### Integrating Custom Security Handlers with AsyncApp Source: https://github.com/spec-first/connexion/blob/main/docs/security.md Initialize AsyncApp with a custom security_map to enable your custom security handlers. ```python from connexion import AsyncApp app = AsyncApp(__name__, security_map=security_map) app.add_api("openapi.yaml", security_map=security_map) ``` -------------------------------- ### GET /api/v1/pets Source: https://context7.com/spec-first/connexion/llms.txt Retrieves a list of all pets, with optional filtering by animal type and a limit on the number of results. ```APIDOC ## GET /api/v1/pets ### Description Retrieves a list of all pets. Supports optional query parameters for filtering by animal type and limiting the number of results. ### Method GET ### Endpoint /api/v1/pets ### Parameters #### Query Parameters - **limit** (integer) - Optional - The maximum number of pets to return. Defaults to 10. - **animal_type** (string) - Optional - Filters the pets to return only those of the specified animal type. ### Response #### Success Response (200) - **array** - A list of pet objects. ### Response Example ```json [ { "id": 1, "name": "Buddy", "animal_type": "dog", "created": "2023-10-27T10:00:00Z" } ] ``` ``` -------------------------------- ### GET /foo Endpoint Source: https://github.com/spec-first/connexion/blob/main/docs/request.md This endpoint is defined in Swagger 2 format and includes query parameters for filtering. ```APIDOC ## GET /foo ### Description Retrieves data with optional filtering. ### Method GET ### Endpoint /foo ### Parameters #### Query Parameters - **filter** (string) - Required - Some filter. - **FilterOption** (string) - Optional - Some filter option. ### Request Example ```json { "example": "request body" } ``` ### Response #### Success Response (200) - **example** (string) - Description of the example response field. #### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### AsyncApp with Custom Validator Map Source: https://github.com/spec-first/connexion/blob/main/docs/validation.md Shows how to initialize an AsyncApp with a custom validator map, ensuring custom validation logic is applied to API requests. ```python from connexion import AsyncApp app = AsyncApp(__name__, validator_map=validator_map) app.add_api("openapi.yaml", validator_map=validator_map) ``` -------------------------------- ### Lifespan Events for Startup and Shutdown Source: https://context7.com/spec-first/connexion/llms.txt Register handlers for application startup and shutdown events to manage resources like database connections. ```python import contextlib import typing from connexion import AsyncApp, ConnexionMiddleware, request # Simulated database client class DatabaseClient: def __init__(self): self.connected = False async def connect(self): self.connected = True print("Database connected") async def disconnect(self): self.connected = False print("Database disconnected") async def query(self, sql): return {"result": "data"} @contextlib.asynccontextmanager async def lifespan_handler(app: ConnexionMiddleware) -> typing.AsyncIterator: """Setup and teardown resources.""" # Startup: Initialize resources db = DatabaseClient() await db.connect() # Yield state that will be available on request.state yield {"db": db} # Shutdown: Cleanup resources await db.disconnect() async def get_data(): """Access lifespan state in endpoint.""" db = request.state.db result = await db.query("SELECT * FROM data") return result app = AsyncApp(__name__, lifespan=lifespan_handler) app.add_api("openapi.yaml") ``` -------------------------------- ### Swagger 2 Query Parameter Specification Source: https://github.com/spec-first/connexion/blob/main/docs/request.md Example of defining a required query parameter 'message' in a Swagger 2 path specification. ```yaml paths: /foo: get: operationId: api.foo_get parameters: - name: message description: Some message. in: query type: string required: true ``` -------------------------------- ### OpenAPI 3 Query Parameter Specification Source: https://github.com/spec-first/connexion/blob/main/docs/request.md Example of defining a required query parameter 'message' in an OpenAPI 3 path specification. ```yaml paths: /foo: get: operationId: api.foo_get parameters: - name: message description: Some message. in: query schema: type: string required: true ``` -------------------------------- ### OpenAPI Specification with Modified Server URL Source: https://github.com/spec-first/connexion/blob/main/examples/reverseproxy/README.rst Example OpenAPI specification showing a server URL modified by a reverse proxy path. ```json { "servers" : [ { "url" : "/banana/openapi" } ], "paths" : { "/hello" : { "get" : { "responses" : { "200" : { "description" : "hello", "content" : { "text/plain" : { "schema" : { "type" : "string" } } } } }, "operationId" : "app.hello", "summary" : "say hi" } } }, "openapi" : "3.0.0", "info" : { "version" : "1.0", "title" : "Path-Altering Reverse Proxy Example" } } ``` -------------------------------- ### Wrap Existing App with ConnexionMiddleware Source: https://github.com/spec-first/connexion/blob/main/README.md Integrate Connexion functionality into an existing ASGI or WSGI application using ConnexionMiddleware. ```Python from asgi_framework import App from connexion import ConnexionMiddleware app = App(__name__) app = ConnexionMiddleware(app) ``` -------------------------------- ### Run ASGI app with root path using gunicorn Source: https://github.com/spec-first/connexion/blob/main/docs/cookbook.md Use gunicorn with the uvicorn worker to manage a stripped path prefix by specifying the --root-path option. ```bash $ gunicorn -k uvicorn.workers.UvicornWorker run:app --root-path ``` -------------------------------- ### Adding ASGI Middleware to Connexion Source: https://context7.com/spec-first/connexion/llms.txt Demonstrates how to add ASGI middleware like CORSMiddleware and GZipMiddleware to a Connexion application using AsyncApp. Middleware can be added before or after exception handling. ```python from pathlib import Path from connexion import AsyncApp from connexion.middleware import MiddlewarePosition from starlette.middleware.cors import CORSMiddleware from starlette.middleware.gzip import GZipMiddleware app = AsyncApp(__name__) # Add CORS middleware app.add_middleware( CORSMiddleware, position=MiddlewarePosition.BEFORE_EXCEPTION, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # Add GZip compression app.add_middleware( GZipMiddleware, position=MiddlewarePosition.BEFORE_EXCEPTION, minimum_size=1000, ) app.add_api("openapi.yaml") if __name__ == "__main__": app.run(f"{Path(__file__).stem}:app", port=8080) ``` -------------------------------- ### Swagger 2 Path Definition Source: https://github.com/spec-first/connexion/blob/main/docs/request.md Defines a GET endpoint '/foo' with query parameters 'filter' and 'FilterOption' using Swagger 2 syntax. ```yaml paths: /foo: get: operationId: api.foo_get parameters: - name: filter description: Some filter. in: query type: string required: true - name: FilterOption description: Some filter option. in: query type: string ``` -------------------------------- ### Configuring Swagger UI Options Source: https://github.com/spec-first/connexion/blob/main/docs/v3.md Instantiate `SwaggerUIOptions` to configure Swagger UI settings like visibility and path. This can be passed to the Connexion App or when adding an API. ```python import connexion from connexion.options import SwaggerUIOptions swagger_ui_options = SwaggerUIOptions( swagger_ui=True, swagger_ui_path="docs", ) app = connexion.FlaskApp(__name__, swagger_ui_options=swagger_ui_options) # either app.add_api("openapi.yaml", swagger_ui_options=swagger_ui_options) # or ``` -------------------------------- ### Configure Swagger UI Path for AsyncApp Source: https://github.com/spec-first/connexion/blob/main/docs/swagger_ui.md Set a custom path for the Swagger UI by initializing SwaggerUIOptions with the desired path and passing it to the AsyncApp constructor and add_api method. ```python from connexion import AsyncApp from connexion.options import SwaggerUIOptions options = SwaggerUIOptions(swagger_ui_path="/docs") app = AsyncApp(__name__, swagger_ui_options=options) app.add_api("openapi.yaml", swagger_ui_options=options) ``` -------------------------------- ### Use ConnexionMiddleware with ASGI App Source: https://context7.com/spec-first/connexion/llms.txt Wrap an existing ASGI application with ConnexionMiddleware to add API functionality. Ensure the specification directory is provided. ```python from connexion import ConnexionMiddleware from starlette.applications import Starlette from starlette.routing import Route # Define your endpoint async def homepage(request): return {"message": "Hello World"} # Create your framework application starlette_app = Starlette(routes=[Route("/", homepage)]) # Wrap with Connexion middleware app = ConnexionMiddleware(starlette_app, specification_dir="spec") app.add_api("openapi.yaml") ``` -------------------------------- ### Swagger 2 Form Data Specification Source: https://github.com/spec-first/connexion/blob/main/docs/request.md Example of defining form data parameters 'field1' and 'field2' in a Swagger 2 specification for a POST request. ```yaml paths: /foo: post: operationId: api.foo_get consumes: - application/json parameters: - in: formData name: field1 type: string - in: formData name: field2 type: string ``` -------------------------------- ### Python Function with Named Body Argument Source: https://github.com/spec-first/connexion/blob/main/docs/request.md Example of a Python function expecting the request body using a name specified by 'x-body-name' in the OpenAPI spec. ```python # Based on x-body-name def foo_get(payload) ... ``` -------------------------------- ### Run Connexion Application (Development) Source: https://github.com/spec-first/connexion/blob/main/README.md Use the `run` method for development purposes. This is not recommended for production environments. ```Python app.run() ``` -------------------------------- ### AsyncApp Array of Files Handling Source: https://github.com/spec-first/connexion/blob/main/docs/request.md When an array of files is defined, AsyncApp provides them as a list of Starlette.UploadFile instances. ```python def foo_get(file) assert isinstance(file, list) assert isinstance(file[0], starlette.UploadFile) ... ``` -------------------------------- ### AsyncApp File Upload Handling Source: https://github.com/spec-first/connexion/blob/main/docs/request.md When using AsyncApp, uploaded files are provided as Starlette.UploadFile instances. ```python def foo_get(file) assert isinstance(file, starlette.UploadFile) ... ``` -------------------------------- ### Class-based Views for Pets API Source: https://context7.com/spec-first/connexion/llms.txt Defines a class-based view for handling /pets endpoints, including search, create, get, update, and delete operations. ```python class PetsView: """View class for /pets endpoints.""" def search(self, limit=100): """GET /pets - List all pets.""" return list(PETS.values())[:limit] def post(self, body): """POST /pets - Create a new pet.""" pet_id = len(PETS) + 1 body["id"] = pet_id PETS[pet_id] = body return body, 201 def get(self, pet_id): """GET /pets/{pet_id} - Get a pet.""" return PETS.get(pet_id) or ({"error": "Not found"}, 404) def put(self, pet_id, body): """PUT /pets/{pet_id} - Update a pet.""" PETS[pet_id] = body return body def delete(self, pet_id): """DELETE /pets/{pet_id} - Delete a pet.""" if pet_id in PETS: del PETS[pet_id] return None, 204 return None, 404 ``` -------------------------------- ### Connexion Context Injection (Individual Keys) Source: https://github.com/spec-first/connexion/blob/main/docs/request.md Demonstrates how to receive specific context keys (user, token_info) directly as arguments in a Python function. ```python def foo_get(user, token_info): ... ``` -------------------------------- ### Run ASGI app with root path using uvicorn Source: https://github.com/spec-first/connexion/blob/main/docs/cookbook.md Configure the uvicorn server to handle a stripped path prefix by setting the --root-path option when running your application. ```bash $ uvicorn run:app --root-path ``` -------------------------------- ### Swagger 2 Path Parameter Definition Source: https://github.com/spec-first/connexion/blob/main/docs/routing.md Example of defining a path parameter 'id' of type integer for the '/users/{id}' path in a Swagger 2 specification. ```yaml paths: /users/{id}: parameters: - in: path name: id # Note the name is the same as in the path required: true type: integer description: The user ID. ``` -------------------------------- ### Run OpenAPI Specification with Stub Source: https://github.com/spec-first/connexion/blob/main/docs/cli.md Use this command to run an OpenAPI specification file, attaching a stub to unavailable operations which will return a '501 Not Implemented' response. ```bash $ connexion run your_api.yaml --stub ``` -------------------------------- ### Run Connexion Server Source: https://github.com/spec-first/connexion/blob/main/examples/restyresolver/README.rst Launches the Connexion server using a Python script. This command assumes your server code is saved in a file named 'resty.py'. ```bash python resty.py ``` -------------------------------- ### Running Connexion 3.0 with uvicorn Source: https://github.com/spec-first/connexion/blob/main/docs/v3.md This command demonstrates how to run a Connexion 3.0 application using the uvicorn ASGI server. ```bash $ uvicorn hello:app ``` -------------------------------- ### Registering Error Handlers in Connexion 2 Source: https://github.com/spec-first/connexion/blob/main/docs/v3.md In Connexion 2, error handlers could be registered on either the Connexion App or the underlying Flask App. This example shows both methods. ```python import connexion def not_found_handler(exc: Exception) -> flask.Response: ... app = connexion.App(__name__) flask_app = app.app app.add_error_handler(404, not_found_handler) # either flask_app.register_error_handler(404, not_found_handler) # or ``` -------------------------------- ### Run application with uvicorn Source: https://github.com/spec-first/connexion/blob/main/docs/quickstart.md Run the Connexion application using the uvicorn ASGI server. Assumes the application object is named 'app' in 'run.py'. ```bash # assuming your application is defined as ``app`` in ``run.py`` $ uvicorn run:app ``` -------------------------------- ### Run Connexion Application with Uvicorn (Production) Source: https://github.com/spec-first/connexion/blob/main/README.md Run your Connexion application in production using an ASGI server like uvicorn. Assumes the app is defined in 'run.py'. ```Shell $ uvicorn run:app ``` -------------------------------- ### FlaskApp Array of Files Handling Source: https://github.com/spec-first/connexion/blob/main/docs/request.md When an array of files is defined, FlaskApp provides them as a list of werkzeug.FileStorage instances. ```python def foo_get(file) assert isinstance(file, list) assert isinstance(file[0], werkzeug.FileStorage) ... ``` -------------------------------- ### Run Connexion Application with Uvicorn Source: https://github.com/spec-first/connexion/blob/main/examples/reverseproxy/README.rst Run your Connexion application using uvicorn with the --factory option. ```bash $ uvicorn --factory app:create_app --port 8080 ``` -------------------------------- ### Access Context Variables in Tests with TestContext Source: https://github.com/spec-first/connexion/blob/main/docs/testing.md Utilize `TestContext` to access Connexion's context variables within your tests. If a context variable is not provided, `TestContext` will generate a dummy one. This example demonstrates accessing the operation method. ```python from unittest.mock import MagicMock from connexion.context import operation from connexion.testing import TestContext def get_method(): """Function called within TestContext you can access the context variables here.""" return operation.method def test(): operation = MagicMock(name="operation") operation.method = "post" with TestContext(operation=operation): assert get_method() == "post ``` -------------------------------- ### Run application with auto-reloading Source: https://github.com/spec-first/connexion/blob/main/docs/quickstart.md Configure the app.run() method to use automatic reloading by providing the application as an import string, typically derived from the current file's stem. ```python from pathlib import Path app.run(f"{Path(__file__).stem}:app") ``` -------------------------------- ### Connexion Context Injection (Full Context) Source: https://github.com/spec-first/connexion/blob/main/docs/request.md Shows how to receive the entire Connexion context dictionary in a Python function by naming the argument 'context_'. ```python def foo_get(context_): ... ``` -------------------------------- ### Set Root Path via ASGI Server Source: https://github.com/spec-first/connexion/blob/main/examples/reverseproxy/README.rst Configure the root path when running your application with an ASGI server like uvicorn. ```bash uvicorn ... --root_path="/reverse_proxied/" ``` -------------------------------- ### Connexion CLI Run Command Usage Source: https://github.com/spec-first/connexion/blob/main/docs/cli.md This shows the basic syntax for the `connexion run` command, specifying the OpenAPI specification file and an optional base module path for handlers. ```bash $ connexion run [OPTIONS] SPEC_FILE [BASE_MODULE_PATH] ``` -------------------------------- ### Create FlaskApp Application Source: https://context7.com/spec-first/connexion/llms.txt Initialize a FlaskApp with a specification directory and register an API. This is useful for migrating from Connexion 2.x. ```python from pathlib import Path from connexion import FlaskApp # Create the application app = FlaskApp(__name__, specification_dir="spec") # Register an API app.add_api("openapi.yaml") # Run the application (development only) if __name__ == "__main__": app.run(f"{Path(__file__).stem}:app", port=8080) ``` -------------------------------- ### AsyncApp with Pythonic Parameters Source: https://github.com/spec-first/connexion/blob/main/docs/request.md Initialize AsyncApp with `pythonic_params=True` to enable automatic conversion of camelCase arguments to snake_case and handle Python built-in name conflicts. ```python from connexion import AsyncApp app = AsyncApp(__name__, pythonic_params=True) app.add_api("openapi.yaml", pythonic_params=True) ``` -------------------------------- ### Connexion CLI Commands Source: https://context7.com/spec-first/connexion/llms.txt Various commands for the Connexion CLI, including running specifications with stub handlers, specifying a base module path, running mock servers, and running from a URL. Use --help for all options. ```bash # Run an OpenAPI specification with stub handlers (returns 501 Not Implemented) connexion run openapi.yaml --stub ``` ```bash # Run with a base module path for handler resolution connexion run openapi.yaml api/ ``` ```bash # Run a mock server that returns example responses connexion run openapi.yaml --mock=all ``` ```bash # Run from a URL connexion run https://example.com/openapi.yaml --mock=all ``` ```bash # Get help for all options connexion run --help ``` -------------------------------- ### Integrating Custom Security Handlers with FlaskApp Source: https://github.com/spec-first/connexion/blob/main/docs/security.md Initialize FlaskApp with a custom security_map to enable your custom security handlers. ```python from connexion import FlaskApp app = FlaskApp(__name__, security_map=security_map) app.add_api("openapi.yaml", security_map=security_map) ``` -------------------------------- ### FlaskApp with Custom Validator Map Source: https://github.com/spec-first/connexion/blob/main/docs/validation.md Demonstrates initializing a FlaskApp with a custom validator map, enabling custom validation rules for API interactions. ```python from connexion import FlaskApp app = FlaskApp(__name__, validator_map=validator_map) app.add_api("openapi.yaml", validator_map=validator_map) ``` -------------------------------- ### Customize Middleware Stack in ConnexionMiddleware Source: https://github.com/spec-first/connexion/blob/main/docs/middleware.md When initializing ConnexionMiddleware, you can pass a custom `middlewares` list to override the default stack. This allows for fine-grained control over the middleware order and inclusion. ```python from asgi_framework import App from connexion import ConnexionMiddleware from connexion.middleware.security import SecurityMiddleware middlewares = [middleware for middleware in ConnexionMiddleware.default_middlewares if middleware is not SecurityMiddleware] app = App(__name__) app = ConnexionMiddleware(app, middlewares=middlewares) ``` -------------------------------- ### Create ConnexionMiddleware with WSGI App Source: https://github.com/spec-first/connexion/blob/main/docs/quickstart.md Wrap a WSGI application using a2wsgi.WSGIMiddleware and then ConnexionMiddleware. This allows Connexion to work with existing WSGI applications. ```python from wsgi_framework import App from connexion import ConnexionMiddleware from a2wsgi import WSGIMiddleware wsgi_app = App(__name__) asgi_app = WSGIMiddleware(wsgi_app) app = ConnexionMiddleware(asgi_app) ``` -------------------------------- ### Run Connexion API Source: https://github.com/spec-first/connexion/blob/main/docs/index.md Use this command to run your Connexion API based on an OpenAPI specification file. ```bash connexion run openapi.yaml ``` -------------------------------- ### Add Middleware to AsyncApp Source: https://github.com/spec-first/connexion/blob/main/docs/middleware.md Use the `add_middleware` method to insert custom ASGI middleware into the AsyncApp stack. Specify the middleware class and any required options. ```python from connexion import AsyncApp app = AsyncApp(__name__) app.add_middleware(MiddlewareClass, **options) ``` -------------------------------- ### API Key Authentication Source: https://context7.com/spec-first/connexion/llms.txt This section demonstrates how to implement API key authentication with a custom validation function. ```APIDOC ## API Key Authentication Implement API key authentication with a custom validation function. ### GET /secret #### Description Access protected resource using API key authentication. #### Method GET #### Endpoint /secret #### Security - api_key: [] #### Response ##### Success Response (200) - (object) - Secret data #### Response Example { "message": "Hello user 100! Here is your secret." } ``` -------------------------------- ### Custom Security Handler Implementation Source: https://github.com/spec-first/connexion/blob/main/docs/security.md Subclass AbstractSecurityHandler to create custom security handlers for unsupported schemes. Define security_definition_key and environ_key for integration. ```python from connexion.security import AbstractSecurityHandler class MyCustomSecurityHandler(AbstractSecurityHandler): security_definition_key = "x-{type}InfoFunc" environ_key = "{TYPE}INFO_FUNC" def _get_verify_func(self, {type}_info_func): ... security_map = { "{type}": MyCustomSecurityHandler, } ``` -------------------------------- ### Integrating Custom Security Handlers with ConnexionMiddleware Source: https://github.com/spec-first/connexion/blob/main/docs/security.md Wrap your ASGI application with ConnexionMiddleware, passing the custom security_map to enable custom security handlers. ```python from asgi_framework import App from connexion import ConnexionMiddleware app = App(__name__) app = ConnexionMiddleware(app, security_map=security_map) app.add_api("openapi.yaml", security_map=security_map) ``` -------------------------------- ### Import Connexion Context Variables Source: https://github.com/spec-first/connexion/blob/main/docs/context.md Import context variables like request, operation, and scope from connexion.context. An alias for connexion.context.request is also available. ```python from connexion.context import context, operation, receive, request, scope from connexion import request # alias for connexion.context.request ``` -------------------------------- ### Running Connexion 3.0 Application with ASGI Source: https://github.com/spec-first/connexion/blob/main/docs/v3.md This is the recommended way to run a Connexion 3.0 application using an ASGI server. Ensure you are using an ASGI server like uvicorn. ```python import connexion app = connexion.App(__name__) if __name__ == "__main__": app.run() ``` -------------------------------- ### Running Connexion 3.0 with gunicorn and UvicornWorker Source: https://github.com/spec-first/connexion/blob/main/docs/v3.md This command shows how to run a Connexion 3.0 application using gunicorn with the UvicornWorker, suitable for ASGI applications. ```bash $ gunicorn -k uvicorn.workers.UvicornWorker hello:app ``` -------------------------------- ### Add Middleware to ConnexionMiddleware Source: https://github.com/spec-first/connexion/blob/main/docs/middleware.md When using ConnexionMiddleware directly, you can add further ASGI middleware using the `add_middleware` method. This allows for a flexible middleware configuration. ```python from asgi_framework import App from connexion import ConnexionMiddleware app = App(__name__) app = ConnexionMiddleware(app) app.add_middleware(MiddlewareClass, **options) ``` -------------------------------- ### FlaskApp File Upload Handling Source: https://github.com/spec-first/connexion/blob/main/docs/request.md When using FlaskApp, uploaded files are provided as werkzeug.FileStorage instances. ```python def foo_get(file) assert isinstance(file, werkzeug.FileStorage) ... ``` -------------------------------- ### Initialize Flask App with MethodViewResolver Source: https://github.com/spec-first/connexion/blob/main/docs/routing.md Instantiate a Connexion Flask app and add an API specification using the MethodViewResolver. This resolver routes requests to class methods of a Flask MethodView subclass. ```python import connexion from connexion.resolver import MethodResolver app = connexion.FlaskApp(__name__) app.add_api('openapi.yaml', resolver=MethodViewResolver('api')) ``` -------------------------------- ### Run application with gunicorn and uvicorn worker Source: https://github.com/spec-first/connexion/blob/main/docs/quickstart.md Run the Connexion application in production using gunicorn with the uvicorn worker. Assumes the application object is named 'app' in 'run.py'. ```bash # assuming your application is defined as ``app`` in ``run.py`` $ gunicorn -k uvicorn.workers.UvicornWorker run:app ```