### Running Flask-RESTful Example with Just Source: https://github.com/straydragon/flask-x-openapi-schema/blob/main/docs/getting_started.md This command executes the basic Flask-RESTful example application, showcasing Flask-X-OpenAPI-Schema's integration with Flask-RESTful. It requires 'just' to be installed and the example application to be set up in the repository. ```bash just run-example-flask-restful ``` -------------------------------- ### Running Flask MethodView Example with Just Source: https://github.com/straydragon/flask-x-openapi-schema/blob/main/docs/getting_started.md This command executes the basic Flask MethodView example application, demonstrating core features of Flask-X-OpenAPI-Schema with Flask's MethodView. It requires 'just' to be installed and the example application to be set up in the repository. ```bash just run-example-flask ``` -------------------------------- ### Installing Flask-X-OpenAPI-Schema with uv Source: https://github.com/straydragon/flask-x-openapi-schema/blob/main/docs/getting_started.md This command installs the core Flask-X-OpenAPI-Schema library using uv, an alternative Python package installer. It's suitable for basic Flask applications without Flask-RESTful. ```bash uv pip install flask-x-openapi-schema ``` -------------------------------- ### Installing Flask-X-OpenAPI-Schema with Flask-RESTful support via uv Source: https://github.com/straydragon/flask-x-openapi-schema/blob/main/docs/getting_started.md This command installs Flask-X-OpenAPI-Schema along with its Flask-RESTful extension using uv. This is required if your application uses Flask-RESTful for API development. ```bash uv pip install flask-x-openapi-schema[flask-restful] ``` -------------------------------- ### Installing Flask-X-OpenAPI-Schema Dependencies (Bash) Source: https://github.com/straydragon/flask-x-openapi-schema/blob/main/examples/README.md This snippet provides commands to install the necessary dependencies for Flask-X-OpenAPI-Schema. It includes installing the package with Flask-RESTful support and the 'rich' library for enhanced console output, which are prerequisites for running the examples. ```bash # Install the package with Flask-RESTful support pip install -e .[flask-restful] # Install rich for pretty console output pip install rich ``` -------------------------------- ### Installing Flask-X-OpenAPI-Schema with pip Source: https://github.com/straydragon/flask-x-openapi-schema/blob/main/docs/getting_started.md This command installs the core Flask-X-OpenAPI-Schema library using pip, the standard Python package installer. It's suitable for basic Flask applications without Flask-RESTful. ```bash pip install flask-x-openapi-schema ``` -------------------------------- ### Installing Flask-X-OpenAPI-Schema with Flask-RESTful support via pip Source: https://github.com/straydragon/flask-x-openapi-schema/blob/main/docs/getting_started.md This command installs Flask-X-OpenAPI-Schema along with its Flask-RESTful extension using pip. This is required if your application uses Flask-RESTful for API development. ```bash pip install flask-x-openapi-schema[flask-restful] ``` -------------------------------- ### Running Flask File Upload Examples with Justfile Commands Source: https://github.com/straydragon/flask-x-openapi-schema/blob/main/docs/file_uploads.md These `bash` commands demonstrate how to execute the provided Flask and Flask-RESTful file upload examples using `justfile`. `just run-example-flask` initiates the Flask MethodView example, while `just run-example-flask-restful` starts the Flask-RESTful example, enabling users to test the file upload functionality locally. ```bash # Run the Flask MethodView example just run-example-flask # Run the Flask-RESTful example just run-example-flask-restful ``` -------------------------------- ### Running the Flask Application Source: https://github.com/straydragon/flask-x-openapi-schema/blob/main/examples/custom_errors/README.md Instructions to navigate to the example directory and start the Flask application using Python. The application will be accessible on localhost:5000. ```bash cd examples/custom_errors python app.py ``` -------------------------------- ### Installing Flask-X-OpenAPI-Schema with pip Source: https://github.com/straydragon/flask-x-openapi-schema/blob/main/docs/usage_guide.md This snippet demonstrates how to install the Flask-X-OpenAPI-Schema library using pip. It includes commands for a basic installation and an extended installation with Flask-RESTful support, which is required for integrating with Flask-RESTful resources. ```bash # Basic installation pip install flask-x-openapi-schema # With Flask-RESTful support pip install flask-x-openapi-schema[flask-restful] ``` -------------------------------- ### Testing Flask-X-OpenAPI-Schema API with cURL (Bash) Source: https://github.com/straydragon/flask-x-openapi-schema/blob/main/examples/README.md This example demonstrates how to test the deployed API endpoints using the `curl` command-line tool. It specifically shows how to make a GET request to retrieve all products from the API, assuming the server is running on `http://localhost:5000`. ```bash # Get all products curl http://localhost:5000/products ``` -------------------------------- ### Initializing Flask-RESTful API with OpenAPI Integration Source: https://github.com/straydragon/flask-x-openapi-schema/blob/main/docs/getting_started.md This snippet initializes a Flask application and integrates `flask-x-openapi-schema` by creating an `OpenAPIApi` class that inherits from `OpenAPIIntegrationMixin` and `Api`. This setup enables automatic OpenAPI schema generation for Flask-RESTful resources. ```Python from flask import Flask from flask_restful import Resource from pydantic import BaseModel, Field from flask_x_openapi_schema.x.flask_restful import openapi_metadata, OpenAPIIntegrationMixin from flask_x_openapi_schema import OpenAPIMetaResponse, OpenAPIMetaResponseItem # Create a Flask app app = Flask(__name__) # Create an OpenAPI-enabled API class OpenAPIApi(OpenAPIIntegrationMixin, Api): pass api = OpenAPIApi(app) ``` -------------------------------- ### Using BaseRespModel for API Responses in Python Source: https://github.com/straydragon/flask-x-openapi-schema/blob/main/docs/getting_started.md This example demonstrates defining structured API responses using `BaseRespModel` and Pydantic. It shows how to instantiate a response object with data and then convert it into a standard Flask response using the `to_response()` method, ensuring consistent output formatting. ```Python from flask_x_openapi_schema import BaseRespModel from pydantic import Field class ItemResponse(BaseRespModel): id: str = Field(..., description="Item ID") name: str = Field(..., description="Item name") description: str = Field(None, description="Item description") price: float = Field(..., description="Item price") @openapi_metadata( summary="Get an item by ID", # ... ) def get(self, item_id: str): # ... response = ItemResponse( id=item_id, name=f"Item {item_id}", description=f"Item {item_id} description", price=float(item_id) * 10.99, ) # Convert to Flask response return response.to_response(200) ``` -------------------------------- ### Running Flask-X-OpenAPI-Schema Examples with Just (Bash) Source: https://github.com/straydragon/flask-x-openapi-schema/blob/main/examples/README.md This section provides `just` commands to conveniently run various Flask-X-OpenAPI-Schema examples. It includes commands for basic Flask MethodView and Flask-RESTful examples, as well as their structured response counterparts, allowing sequential execution or individual runs. ```bash # Run the basic Flask MethodView example just run-example-flask # Run the basic Flask-RESTful example just run-example-flask-restful # Run both basic examples sequentially just run-examples # Run the Flask MethodView response example just run-response-example-flask # Run the Flask-RESTful response example just run-response-example-flask-restful # Run both response examples sequentially just run-response-examples ``` -------------------------------- ### Serving Swagger UI with Flask and JavaScript Source: https://github.com/straydragon/flask-x-openapi-schema/blob/main/docs/getting_started.md This code snippet shows how to serve an interactive Swagger UI documentation interface through a Flask route. It returns an HTML page that embeds the Swagger UI library from a CDN and initializes it to load the OpenAPI specification from the `/openapi.yaml` endpoint. ```HTML @app.route("/") def index(): return """ API Documentation
""" ``` -------------------------------- ### Defining Flask-RESTful Resources with OpenAPI Metadata Source: https://github.com/straydragon/flask-x-openapi-schema/blob/main/docs/usage_guide.md This example illustrates how to create Flask-RESTful `Resource` classes and annotate their methods (`get`, `post`) with `@openapi_metadata`. This decorator allows defining OpenAPI summary, description, tags, operation ID, and detailed response schemas using `OpenAPIMetaResponse` and `OpenAPIMetaResponseItem`. ```python # resources/user_resource.py from flask_restful import Resource from flask_x_openapi_schema.x.flask_restful import openapi_metadata from flask_x_openapi_schema import OpenAPIMetaResponse, OpenAPIMetaResponseItem from my_api.models.request_models import UserCreateRequest, UserUpdateRequest from my_api.models.response_models import UserResponse, ErrorResponse class UserListResource(Resource): @openapi_metadata( summary="Get all users", description="Retrieve a list of all users", tags=["users"], operation_id="getUsers", responses=OpenAPIMetaResponse( responses={ "200": OpenAPIMetaResponseItem( model=UserResponse, description="List of users retrieved successfully", ), "500": OpenAPIMetaResponseItem( model=ErrorResponse, description="Internal server error", ), } ), ) def get(self): # Implementation... users = [ {"id": "1", "username": "user1", "email": "user1@example.com"}, {"id": "2", "username": "user2", "email": "user2@example.com"}, ] return users, 200 @openapi_metadata( summary="Create a new user", description="Create a new user with the provided information", tags=["users"], operation_id="createUser", responses=OpenAPIMetaResponse( responses={ "201": OpenAPIMetaResponseItem( model=UserResponse, description="User created successfully", ), "400": OpenAPIMetaResponseItem( model=ErrorResponse, description="Invalid request data", ), "500": OpenAPIMetaResponseItem( model=ErrorResponse, description="Internal server error", ), } ), ) def post(self, _x_body: UserCreateRequest): # Implementation... user = { "id": "3", "username": _x_body.username, "email": _x_body.email, } return user, 201 class UserResource(Resource): @openapi_metadata( summary="Get a user by ID", description="Retrieve a user by its unique identifier", tags=["users"], operation_id="getUser", responses=OpenAPIMetaResponse( responses={ "200": OpenAPIMetaResponseItem( model=UserResponse, description="User retrieved successfully", ), "404": OpenAPIMetaResponseItem( model=ErrorResponse, description="User not found", ), "500": OpenAPIMetaResponseItem( model=ErrorResponse, description="Internal server error", ), } ), ) def get(self, user_id: str): # Implementation... if user_id not in ["1", "2"]: return {"error_code": "USER_NOT_FOUND", "message": "User not found"}, 404 user = { "id": user_id, "username": f"user{user_id}", "email": f"user{user_id}@example.com", } return user, 200 ``` -------------------------------- ### Serving Swagger UI with Flask Source: https://github.com/straydragon/flask-x-openapi-schema/blob/main/docs/getting_started.md This Flask application snippet defines a root route (/) that serves an HTML page. This page embeds the Swagger UI library from a CDN and configures it to load the OpenAPI specification from /openapi.yaml, providing interactive API documentation. ```Python # Serve Swagger UI @app.route("/") def index(): return """ API Documentation
""" if __name__ == "__main__": app.run(debug=True) ``` -------------------------------- ### Running Flask-X-OpenAPI-Schema Examples Source: https://github.com/straydragon/flask-x-openapi-schema/blob/main/docs/schema_generation.md These `just` commands are used to run the provided example applications for Flask-X-OpenAPI-Schema. The first command runs the Flask MethodView example, and the second runs the Flask-RESTful example, demonstrating schema generation and API documentation. ```bash # Run the Flask MethodView example just run-example-flask # Run the Flask-RESTful example just run-example-flask-restful ``` -------------------------------- ### Defining Flask-RESTful ItemListResource with OpenAPI Metadata Source: https://github.com/straydragon/flask-x-openapi-schema/blob/main/docs/getting_started.md This `ItemListResource` defines API endpoints for retrieving all items (GET) and creating a new item (POST). The `@openapi_metadata` decorator automatically generates OpenAPI documentation, including summaries, descriptions, tags, operation IDs, and response schemas using Pydantic models. ```Python class ItemListResource(Resource): @openapi_metadata( summary="Get all items", description="Retrieve a list of all items", tags=["items"], operation_id="getItems", responses=OpenAPIMetaResponse( responses={ "200": OpenAPIMetaResponseItem( model=ItemResponse, description="List of items retrieved successfully" ) } ) ) def get(self): # Implementation... items = [ {"id": "1", "name": "Item 1", "description": "First item", "price": 10.99}, {"id": "2", "name": "Item 2", "description": "Second item", "price": 20.99} ] return items, 200 @openapi_metadata( summary="Create a new item", description="Create a new item with the provided information", tags=["items"], operation_id="createItem", responses=OpenAPIMetaResponse( responses={ "201": OpenAPIMetaResponseItem( model=ItemResponse, description="Item created successfully" ), "400": OpenAPIMetaResponseItem( description="Invalid request data" ) } ) ) def post(self, _x_body: ItemRequest): # Implementation... # _x_body is automatically populated from the request JSON item = { "id": "3", "name": _x_body.name, "description": _x_body.description, "price": _x_body.price } return item, 201 ``` -------------------------------- ### Running Flask-X-OpenAPI-Schema Examples with Justfile Source: https://github.com/straydragon/flask-x-openapi-schema/blob/main/docs/parameter_binding.md This snippet provides `justfile` commands to execute the example applications for Flask-X-OpenAPI-Schema. These commands demonstrate how to run the Flask MethodView and Flask-RESTful examples, which showcase various parameter binding functionalities. ```bash # Run the Flask MethodView example just run-example-flask # Run the Flask-RESTful example just run-example-flask-restful ``` -------------------------------- ### Implementing Flask MethodView with OpenAPI Schema Generation Source: https://github.com/straydragon/flask-x-openapi-schema/blob/main/docs/getting_started.md This comprehensive example demonstrates how to integrate Flask-X-OpenAPI-Schema with Flask's MethodView. It defines Pydantic models for request/response bodies, applies OpenAPI metadata to HTTP methods using @openapi_metadata, and sets up a route to dynamically generate and serve the OpenAPI YAML specification for the defined API. ```python from flask import Flask, Blueprint, jsonify from flask.views import MethodView from pydantic import BaseModel, Field from flask_x_openapi_schema.x.flask import openapi_metadata, OpenAPIMethodViewMixin from flask_x_openapi_schema import OpenAPIMetaResponse, OpenAPIMetaResponseItem # Define request and response models class ItemRequest(BaseModel): name: str = Field(..., description="Item name") description: str = Field(None, description="Item description") price: float = Field(..., description="Item price") class ItemResponse(BaseModel): id: str = Field(..., description="Item ID") name: str = Field(..., description="Item name") description: str = Field(None, description="Item description") price: float = Field(..., description="Item price") # Create a Flask app app = Flask(__name__) blueprint = Blueprint("api", __name__, url_prefix="/api") # Create a MethodView class class ItemView(OpenAPIMethodViewMixin, MethodView): @openapi_metadata( summary="Get all items", description="Retrieve a list of all items", tags=["items"], operation_id="getItems", responses=OpenAPIMetaResponse( responses={ "200": OpenAPIMetaResponseItem( model=ItemResponse, description="List of items retrieved successfully", ), } ), ) def get(self): # Implementation... items = [ {"id": "1", "name": "Item 1", "description": "First item", "price": 10.99}, {"id": "2", "name": "Item 2", "description": "Second item", "price": 20.99}, ] return jsonify(items), 200 @openapi_metadata( summary="Create a new item", description="Create a new item with the provided information", tags=["items"], operation_id="createItem", responses=OpenAPIMetaResponse( responses={ "201": OpenAPIMetaResponseItem( model=ItemResponse, description="Item created successfully", ), "400": OpenAPIMetaResponseItem( description="Invalid request data", ), } ), ) def post(self, _x_body: ItemRequest): # Implementation... # _x_body is automatically populated from the request JSON item = { "id": "3", "name": _x_body.name, "description": _x_body.description, "price": _x_body.price, } return jsonify(item), 201 # Register the view ItemView.register_to_blueprint(blueprint, "/items", "items") # Register the blueprint app.register_blueprint(blueprint) # Generate OpenAPI schema @app.route("/openapi.yaml") def get_openapi_spec(): from flask_x_openapi_schema.x.flask.views import MethodViewOpenAPISchemaGenerator import yaml generator = MethodViewOpenAPISchemaGenerator( title="My API", version="1.0.0", description="API for managing items", ) # Process MethodView resources generator.process_methodview_resources(blueprint) # Generate the schema schema = generator.generate_schema() # Convert to YAML yaml_content = yaml.dump(schema, sort_keys=False, default_flow_style=False) return yaml_content, 200, {"Content-Type": "text/yaml"} ``` -------------------------------- ### Retrieving a Product by ID using cURL Source: https://github.com/straydragon/flask-x-openapi-schema/blob/main/examples/README.md This cURL command sends a GET request to retrieve a specific product resource by its unique ID. The '' placeholder in the URL should be replaced with an actual product identifier obtained from a previous creation or listing operation. ```Bash curl http://localhost:5000/products/ ``` -------------------------------- ### Running Flask-X-OpenAPI-Schema Examples Directly (Python) Source: https://github.com/straydragon/flask-x-openapi-schema/blob/main/examples/README.md This snippet shows how to directly execute the Flask-X-OpenAPI-Schema examples using Python's module execution. It provides commands for running the basic Flask and Flask-RESTful applications, as well as their respective structured response examples, bypassing the `just` command. ```python # Run the basic Flask MethodView example python -m examples.flask.app # Run the basic Flask-RESTful example python -m examples.flask_restful.app # Run the Flask MethodView response example python -m examples.flask.response_example # Run the Flask-RESTful response example python -m examples.flask_restful.response_example ``` -------------------------------- ### Binding Path Parameters in Flask-X-OpenAPI-Schema (Python) Source: https://github.com/straydragon/flask-x-openapi-schema/blob/main/docs/getting_started.md This example demonstrates how Flask-X-OpenAPI-Schema automatically binds path parameters from the URL to function arguments. The `item_id` argument directly receives the value from the URL path, simplifying access to dynamic segments of the route. ```Python @openapi_metadata( summary="Get an item by ID", # ... ) def get(self, item_id: str): # item_id is automatically populated from the path parameter if item_id not in ["1", "2"]: return {"error": "Item not found"}, 404 item = { "id": item_id, "name": f"Item {item_id}", "description": f"Item {item_id} description", "price": float(item_id) * 10.99, } return item, 200 ``` -------------------------------- ### Running Flask-X-OpenAPI-Schema Internationalization Examples (Bash) Source: https://github.com/straydragon/flask-x-openapi-schema/blob/main/docs/internationalization.md These Bash commands provide a quick way to run the example applications demonstrating internationalization features in Flask-X-OpenAPI-Schema. They utilize 'justfile' commands to launch the Flask MethodView and Flask-RESTful examples, allowing users to observe multilingual string definitions and OpenAPI metadata generation in action. ```bash # Run the Flask MethodView example just run-example-flask # Run the Flask-RESTful example just run-example-flask-restful ``` -------------------------------- ### Installing Flask-X-OpenAPI-Schema with uv pip Source: https://github.com/straydragon/flask-x-openapi-schema/blob/main/README.md This snippet demonstrates how to install the Flask-X-OpenAPI-Schema package using `uv pip`. It shows both the basic installation and an optional installation with Flask-RESTful support, which includes additional dependencies for Flask-RESTful integration. ```bash # Install the package uv pip install flask-x-openapi-schema # With Flask-RESTful support uv pip install flask-x-openapi-schema[flask-restful] ``` -------------------------------- ### Installing Flask-X-OpenAPI-Schema with uv pip Source: https://github.com/straydragon/flask-x-openapi-schema/blob/main/docs/index.md This snippet demonstrates how to install the Flask-X-OpenAPI-Schema package using `uv pip`. It includes instructions for a basic installation and an extended installation with Flask-RESTful support, ensuring all necessary dependencies are included for different use cases. ```bash # Install the package uv pip install flask-x-openapi-schema # With Flask-RESTful support uv pip install flask-x-openapi-schema[flask-restful] ``` -------------------------------- ### Running Flask-X-OpenAPI-Schema Response Examples (Bash) Source: https://github.com/straydragon/flask-x-openapi-schema/blob/main/docs/response_handling.md This snippet provides bash commands to execute the example applications demonstrating response handling in flask-x-openapi-schema. It uses the just command-runner to simplify the execution of Flask MethodView and Flask-RESTful response examples, allowing users to quickly see the structured response system in action. ```bash # Run the Flask MethodView response example just run-response-example-flask # Run the Flask-RESTful response example just run-response-example-flask-restful ``` -------------------------------- ### Registering Flask-RESTful Resources with OpenAPI API Source: https://github.com/straydragon/flask-x-openapi-schema/blob/main/docs/getting_started.md This snippet registers the `ItemListResource` and `ItemResource` with the `OpenAPIApi` instance. This makes the defined API endpoints accessible at `/api/items` and `/api/items/`, respectively, enabling the OpenAPI schema generation for these routes. ```Python # Register the resources api.add_resource(ItemListResource, "/api/items") api.add_resource(ItemResource, "/api/items/") ``` -------------------------------- ### Accessing Protected Resource (cURL) Source: https://github.com/straydragon/flask-x-openapi-schema/blob/main/examples/custom_errors/README.md cURL commands to test the GET /protected endpoint, which requires Bearer token authentication. Examples include no token, an invalid token, and a valid token to demonstrate different authentication error scenarios and success. ```bash curl http://localhost:5000/protected # Authentication error curl -H "Authorization: Bearer invalid-token" http://localhost:5000/protected # Invalid token error curl -H "Authorization: Bearer valid-token" http://localhost:5000/protected # Success ``` -------------------------------- ### Querying User by ID (cURL) Source: https://github.com/straydragon/flask-x-openapi-schema/blob/main/examples/custom_errors/README.md cURL commands to test the GET /users/{user_id} endpoint. Demonstrates both a successful retrieval and a 404 Not Found error for a non-existent user. ```bash curl http://localhost:5000/users/1 curl http://localhost:5000/users/999 # Not found error ``` -------------------------------- ### Generating OpenAPI Schema in Python Source: https://github.com/straydragon/flask-x-openapi-schema/blob/main/docs/getting_started.md This snippet demonstrates how to generate an OpenAPI YAML specification from your Flask API using `api.generate_openapi_schema`. It configures the schema with a title, version, and description, then converts the generated JSON schema to YAML for serving via a Flask route. ```Python @app.route("/openapi.yaml") def get_openapi_spec(): import yaml schema = api.generate_openapi_schema( title="My API", version="1.0.0", description="API for managing items", output_format="json", ) # Convert to YAML yaml_content = yaml.dump(schema, sort_keys=False, default_flow_style=False) return yaml_content, 200, {"Content-Type": "text/yaml"} ``` -------------------------------- ### Handling Basic File Uploads in Flask-X-OpenAPISchema (Python) Source: https://github.com/straydragon/flask-x-openapi-schema/blob/main/docs/usage_guide.md This example shows a basic file upload using `ImageUploadModel`. The uploaded file is automatically populated into `_x_file.file`, which can then be saved to the server. It returns a success message upon completion. ```python from flask_x_openapi_schema import ImageUploadModel @openapi_metadata( summary="Upload an item image", # ... ) def post(self, item_id: str, _x_file: ImageUploadModel): # _x_file.file is automatically populated from the uploaded file file = _x_file.file # Save the file file.save(f"uploads/{item_id}_{file.filename}") return {"message": "File uploaded successfully"}, 201 ``` -------------------------------- ### Handling File Uploads with _x_file Prefix in Python Source: https://github.com/straydragon/flask-x-openapi-schema/blob/main/docs/getting_started.md This snippet shows how to handle file uploads using the `_x_file` prefix and a dedicated model like `ImageUploadModel`. The `_x_file.file` attribute provides access to the uploaded file object, allowing operations like saving the file to disk. ```Python from flask_x_openapi_schema import ImageUploadModel @openapi_metadata( summary="Upload an item image", # ... ) def post(self, item_id: str, _x_file: ImageUploadModel): # _x_file.file is automatically populated from the uploaded file file = _x_file.file # Save the file file.save(f"uploads/{item_id}_{file.filename}") return {"message": "File uploaded successfully"}, 201 ``` -------------------------------- ### Defining Flask-RESTful ItemResource with OpenAPI Metadata Source: https://github.com/straydragon/flask-x-openapi-schema/blob/main/docs/getting_started.md This `ItemResource` defines an API endpoint for retrieving a single item by its ID. The `@openapi_metadata` decorator provides OpenAPI documentation for this operation, including expected responses for success (200) and not found (404) scenarios. ```Python class ItemResource(Resource): @openapi_metadata( summary="Get an item by ID", description="Retrieve an item by its unique identifier", tags=["items"], operation_id="getItem", responses=OpenAPIMetaResponse( responses={ "200": OpenAPIMetaResponseItem( model=ItemResponse, description="Item retrieved successfully" ), "404": OpenAPIMetaResponseItem( description="Item not found" ) } ) ) def get(self, item_id: str): # Implementation... if item_id not in ["1", "2"]: return {"error": "Item not found"}, 404 item = { "id": item_id, "name": f"Item {item_id}", "description": f"Item {item_id} description", "price": float(item_id) * 10.99 } return item, 200 ``` -------------------------------- ### Configuring Global Prefixes with Flask-X-OpenAPI-Schema (Python) Source: https://github.com/straydragon/flask-x-openapi-schema/blob/main/docs/api/index.md This snippet demonstrates the basic setup for Flask-X-OpenAPI-Schema, including initializing a Flask application and configuring global prefix settings for request body, query, and path parameters using `ConventionalPrefixConfig`. This setup ensures that `openapi_metadata` can correctly bind parameters from incoming requests. ```python from flask import Flask from flask_x_openapi_schema.core.config import ConventionalPrefixConfig, configure_prefixes from flask_x_openapi_schema.x.flask import openapi_metadata # Configure global prefix settings config = ConventionalPrefixConfig( request_body_prefix="body", request_query_prefix="query", request_path_prefix="path" ) configure_prefixes(config) app = Flask(__name__) ``` -------------------------------- ### Running Flask Benchmarks with Locust Source: https://github.com/straydragon/flask-x-openapi-schema/blob/main/benchmarks/README.md This snippet provides a sequence of Bash commands to start a Flask benchmark server, run a Locust load test against it, and then terminate the server. It's used to measure the performance of Flask applications with `flask-x-openapi-schema`. ```bash # Start the Flask server python -m benchmarks.flask.app & # Run the Locust load test locust -f benchmarks/flask/locustfile.py --headless -u 100 -r 10 -t 30s --csv=benchmarks/results/flask # Kill the server kill $! ``` -------------------------------- ### Serving Swagger UI with Flask-X-OpenAPI-Schema (Python) Source: https://github.com/straydragon/flask-x-openapi-schema/blob/main/docs/usage_guide.md This snippet demonstrates how to set up a Flask route to serve the Swagger UI. It embeds the necessary HTML, CSS, and JavaScript to render the API documentation, configuring Swagger UI to fetch the OpenAPI specification from the '/openapi.yaml' endpoint. ```python @app.route("/") def index(): return """ API Documentation
""" ``` -------------------------------- ### Typical Project Structure for Flask-X-OpenAPI-Schema Source: https://github.com/straydragon/flask-x-openapi-schema/blob/main/docs/usage_guide.md This snippet illustrates a recommended project directory structure for applications using Flask-X-OpenAPI-Schema. It organizes API components into `models`, `resources`, `views`, and `utils` directories, promoting modularity and maintainability for larger Flask applications. ```text my_api/ ├── __init__.py ├── app.py ├── models/ │ ├── __init__.py │ ├── request_models.py │ └── response_models.py ├── resources/ │ ├── __init__.py │ ├── user_resource.py │ └── item_resource.py ├── views/ │ ├── __init__.py │ ├── user_view.py │ └── item_view.py └── utils/ ├── __init__.py └── schema_utils.py ``` -------------------------------- ### Uploading a Product Audio File using cURL Source: https://github.com/straydragon/flask-x-openapi-schema/blob/main/examples/README.md This cURL command sends a POST request to upload an audio file associated with a specific product. The '' placeholder should be replaced with the product's ID, and '@/path/to/audio.mp3' must be updated to the actual local path of the audio file. ```Bash curl -X POST http://localhost:5000/products//audio \ -F "audio=@/path/to/audio.mp3" ``` -------------------------------- ### Handling Responses with BaseRespModel (Python) Source: https://github.com/straydragon/flask-x-openapi-schema/blob/main/docs/usage_guide.md This example illustrates using `BaseRespModel` from `flask-x-openapi-schema` along with Pydantic for structured API responses. It shows how to define a response model (`ItemResponse`) and an error response (`ErrorResponse`), and how to return them using `.to_response()` for automatic serialization and status code handling. ```Python from flask_x_openapi_schema import BaseRespModel from pydantic import Field class ItemResponse(BaseRespModel): id: str = Field(..., description="Item ID") name: str = Field(..., description="Item name") description: str = Field(None, description="Item description") price: float = Field(..., description="Item price") @openapi_metadata( summary="Get an item by ID", # ... ) def get(self, item_id: str): # Implementation... if item_id not in ["123", "456"]: error = ErrorResponse( error_code="ITEM_NOT_FOUND", message="Item not found", ) return error.to_response(404) item = ItemResponse( id=item_id, name=f"Item {item_id}", description=f"Description for item {item_id}", price=float(item_id), ) return item.to_response(200) ``` -------------------------------- ### Configuring Custom Parameter Prefixes (Python) Source: https://github.com/straydragon/flask-x-openapi-schema/blob/main/docs/usage_guide.md This example shows how to customize the automatic parameter prefixes (e.g., `_x_body`, `_x_query`) using `ConventionalPrefixConfig`. By creating a custom configuration and passing it to `@openapi_metadata`, developers can define their preferred prefixes for request body, query, path, and file parameters. ```Python from flask_x_openapi_schema import ConventionalPrefixConfig # Create a custom configuration custom_config = ConventionalPrefixConfig( request_body_prefix="req_body", request_query_prefix="req_query", request_path_prefix="req_path", request_file_prefix="req_file" ) @openapi_metadata( summary="Create a new item", prefix_config=custom_config, # ... ) def post(self, req_body: ItemCreateRequest): # req_body is automatically populated from the request JSON item = { "id": "123", "name": req_body.name, "description": req_body.description, "price": req_body.price, } return item, 201 ``` -------------------------------- ### Creating a User (cURL) Source: https://github.com/straydragon/flask-x-openapi-schema/blob/main/examples/custom_errors/README.md cURL commands to test the POST /users endpoint. Shows how to create a new user with valid JSON data and how to trigger a validation error with invalid input. ```bash curl -X POST http://localhost:5000/users \ -H "Content-Type: application/json" \ -d '{"username": "johndoe", "email": "john@example.com", "age": 25}' # Validation error curl -X POST http://localhost:5000/users \ -H "Content-Type: application/json" \ -d '{"username": "j", "email": "invalid-email", "age": 17}' ``` -------------------------------- ### Integrating OpenAPI Metadata with Flask-RESTful Resources in Python Source: https://github.com/straydragon/flask-x-openapi-schema/blob/main/docs/core_components.md This example shows how to apply `openapi_metadata` to methods within a Flask-RESTful `Resource` class. It defines `get` and `put` methods for an `ItemResource`, demonstrating how to document individual API operations for automatic OpenAPI schema generation when using Flask-RESTful. ```python from flask_restful import Resource from flask_x_openapi_schema.x.flask_restful import openapi_metadata class ItemResource(Resource): @openapi_metadata( summary="Get an item", # ... ) def get(self, item_id: str): # Implementation... @openapi_metadata( summary="Update an item", # ... ) def put(self, item_id: str, _x_body: ItemRequest): # Implementation... # Register the resource api.add_resource(ItemResource, "/items/") ``` -------------------------------- ### Adding Descriptions to Pydantic Fields for OpenAPI (Python) Source: https://github.com/straydragon/flask-x-openapi-schema/blob/main/docs/usage_guide.md This example illustrates how to use 'pydantic.Field' with the 'description' argument to add detailed explanations for each field in a Pydantic model. These descriptions are automatically incorporated into the generated OpenAPI schema, providing clear documentation for API request and response bodies. ```python from pydantic import BaseModel, Field class UserCreateRequest(BaseModel): username: str = Field(..., description="User's username") email: str = Field(..., description="User's email address") password: str = Field(..., description="User's password") full_name: str = Field(None, description="User's full name") ``` -------------------------------- ### Uploading a Product Document using cURL Source: https://github.com/straydragon/flask-x-openapi-schema/blob/main/examples/README.md This cURL command sends a POST request to upload a document file associated with a specific product. The '' placeholder should be replaced with the product's ID, and '@/path/to/document.pdf' must be updated to the actual local path of the document file. ```Bash curl -X POST http://localhost:5000/products//documents \ -F "document=@/path/to/document.pdf" ``` -------------------------------- ### Defining API Endpoints with Flask MethodView and OpenAPI Metadata Source: https://github.com/straydragon/flask-x-openapi-schema/blob/main/docs/usage_guide.md This Python snippet illustrates how to define API endpoints using Flask's `MethodView` integrated with `Flask-X-OpenAPI-Schema`. It demonstrates decorating `get` and `post` methods with `openapi_metadata` to provide summary, description, tags, operation ID, and detailed response schemas, including model definitions for successful and error responses. ```python # views/user_view.py from flask.views import MethodView from flask import jsonify from flask_x_openapi_schema.x.flask import openapi_metadata, OpenAPIMethodViewMixin from flask_x_openapi_schema import OpenAPIMetaResponse, OpenAPIMetaResponseItem from my_api.models.request_models import UserCreateRequest, UserUpdateRequest from my_api.models.response_models import UserResponse, ErrorResponse class UserView(OpenAPIMethodViewMixin, MethodView): @openapi_metadata( summary="Get all users", description="Retrieve a list of all users", tags=["users"], operation_id="getUsers", responses=OpenAPIMetaResponse( responses={ "200": OpenAPIMetaResponseItem( model=UserResponse, description="List of users retrieved successfully" ), "500": OpenAPIMetaResponseItem( model=ErrorResponse, description="Internal server error" ) } ) ) def get(self): # Implementation... users = [ {"id": "1", "username": "user1", "email": "user1@example.com"}, {"id": "2", "username": "user2", "email": "user2@example.com"} ] return jsonify(users), 200 @openapi_metadata( summary="Create a new user", description="Create a new user with the provided information", tags=["users"], operation_id="createUser", responses=OpenAPIMetaResponse( responses={ "201": OpenAPIMetaResponseItem( model=UserResponse, description="User created successfully" ), "400": OpenAPIMetaResponseItem( model=ErrorResponse, description="Invalid request data" ), "500": OpenAPIMetaResponseItem( model=ErrorResponse, description="Internal server error" ) } ) ) def post(self, _x_body: UserCreateRequest): # Implementation... user = { "id": "3", "username": _x_body.username, "email": _x_body.email } return jsonify(user), 201 ``` -------------------------------- ### Uploading a Product Image using cURL Source: https://github.com/straydragon/flask-x-openapi-schema/blob/main/examples/README.md This cURL command sends a POST request to upload an image file associated with a specific product. The '' placeholder should be replaced with the product's ID, and '@/path/to/image.jpg' must be updated to the actual local path of the image file. ```Bash curl -X POST http://localhost:5000/products//images \ -F "image=@/path/to/image.jpg" ``` -------------------------------- ### Integrating OpenAPI Metadata with Flask MethodView in Python Source: https://github.com/straydragon/flask-x-openapi-schema/blob/main/docs/core_components.md This example illustrates integrating `OpenAPIMethodViewMixin` with Flask's `MethodView` to apply OpenAPI metadata to HTTP methods. It shows how to define `get` and `post` methods within a class-based view and register it to a Flask blueprint, allowing for automatic OpenAPI schema generation based on method decorators. ```python from flask.views import MethodView from flask_x_openapi_schema.x.flask import OpenAPIMethodViewMixin, openapi_metadata class ItemView(OpenAPIMethodViewMixin, MethodView): @openapi_metadata( summary="Get all items", # ... ) def get(self): # Implementation... @openapi_metadata( summary="Create a new item", # ... ) def post(self, _x_body: ItemRequest): # Implementation... # Register the view ItemView.register_to_blueprint(blueprint, "/items", "items") ``` -------------------------------- ### Binding Query Parameters with _x_query Prefix in Python Source: https://github.com/straydragon/flask-x-openapi-schema/blob/main/docs/getting_started.md This snippet illustrates how to bind URL query parameters to a Pydantic model using the `_x_query` prefix. The `ItemQueryParams` model defines the expected query parameters, and the framework automatically populates the `_x_query` argument, enabling easy access and filtering based on the provided parameters. ```Python class ItemQueryParams(BaseModel): category: str = Field(None, description="Filter by category") min_price: float = Field(None, description="Minimum price") max_price: float = Field(None, description="Maximum price") @openapi_metadata( summary="Get all items", # ... ) def get(self, _x_query: ItemQueryParams = None): # _x_query is automatically populated from the query parameters items = [...] if _x_query: if _x_query.category: items = [item for item in items if item["category"] == _x_query.category] if _x_query.min_price is not None: items = [item for item in items if item["price"] >= _x_query.min_price] if _x_query.max_price is not None: items = [item for item in items if item["price"] <= _x_query.max_price] return items, 200 ``` -------------------------------- ### Deleting a Product by ID using cURL Source: https://github.com/straydragon/flask-x-openapi-schema/blob/main/examples/README.md This cURL command sends a DELETE request to remove a product resource identified by its unique ID. The '' placeholder must be replaced with the actual ID of the product to be deleted from the system. ```Bash curl -X DELETE http://localhost:5000/products/ ``` -------------------------------- ### Generating OpenAPI Specification in Flask Source: https://github.com/straydragon/flask-x-openapi-schema/blob/main/docs/usage_guide.md This snippet demonstrates how to set up a Flask route to dynamically generate and serve the OpenAPI specification in YAML format. It uses `MethodViewOpenAPISchemaGenerator` to process API resources and `yaml.dump` to convert the schema to YAML. ```python from flask_x_openapi_schema.x.flask.views import MethodViewOpenAPISchemaGenerator import yaml @app.route("/openapi.yaml") def get_openapi_spec(): generator = MethodViewOpenAPISchemaGenerator( title="My API", version="1.0.0", description="API for managing users and items", ) # Process MethodView resources generator.process_methodview_resources(blueprint) # Generate the schema schema = generator.generate_schema() # Convert to YAML yaml_content = yaml.dump( schema, sort_keys=False, default_flow_style=False, allow_unicode=True, ) return yaml_content, 200, {"Content-Type": "text/yaml"} ``` -------------------------------- ### Uploading a Product Video File using cURL Source: https://github.com/straydragon/flask-x-openapi-schema/blob/main/examples/README.md This cURL command sends a POST request to upload a video file associated with a specific product. The '' placeholder should be replaced with the product's ID, and '@/path/to/video.mp4' must be updated to the actual local path of the video file. ```Bash curl -X POST http://localhost:5000/products//video \ -F "video=@/path/to/video.mp4" ```