### Install APIFairy (Bash) Source: https://apifairy.readthedocs.io/en/latest/_sources/intro This command installs the APIFairy package using pip, the Python package installer. Ensure you have pip installed and accessible in your environment. ```bash pip install apifairy ``` -------------------------------- ### Install APIFairy - Shell Source: https://apifairy.readthedocs.io/en/latest/intro Installs the APIFairy package using pip. This is the initial step before integrating APIFairy into a Flask application. ```shell pip install apifairy ``` -------------------------------- ### Example API Endpoint with APIFairy Decorators Source: https://apifairy.readthedocs.io/en/latest/_sources/intro This example demonstrates how to use APIFairy decorators to define an API endpoint, including authentication, request body schema, response schema, and other possible responses. ```APIDOC ## PUT /posts/ ### Description Edit an existing post. ### Method PUT ### Endpoint /posts/ ### Parameters #### Path Parameters - **id** (integer) - Required - The ID of the post to edit. #### Query Parameters None #### Request Body - **update_post_schema** (object) - Required - The schema defining the fields to update in the post. ### Request Example ```json { "title": "Updated Post Title", "content": "Updated post content." } ``` ### Response #### Success Response (200) - **post_schema** (object) - The schema defining the updated post details. #### Response Example ```json { "id": 1, "title": "Updated Post Title", "content": "Updated post content.", "created_at": "2023-10-27T10:00:00Z", "updated_at": "2023-10-27T10:30:00Z" } ``` #### Error Responses - **404**: 'Post not found' ``` -------------------------------- ### Initialize APIFairy with Flask App Source: https://apifairy.readthedocs.io/en/latest/guide Initialize the APIFairy extension with your Flask application instance. This step is crucial for APIFairy to integrate with your Flask app and start processing decorators and documentation. ```python from apifairy import APIFairy apifairy = APIFairy() def create_app(): app = Flask(__name__) app.config['APIFAIRY_TITLE'] = 'My API Project' app.config['APIFAIRY_VERSION'] = '1.0' apifairy.init_app(app) return app ``` -------------------------------- ### Two-Phase Initialization of APIFairy (Python) Source: https://apifairy.readthedocs.io/en/latest/_sources/intro This snippet shows the two-phase initialization pattern for APIFairy, which is useful for more complex Flask application setups, such as those using application factories. The APIFairy instance is created first, and then later associated with the Flask app using `init_app`. ```Python from flask import Flask from apifairy import APIFairy apifairy = APIFairy() def create_app(): app = Flask(__name__) apifairy.init_app(app) return app ``` -------------------------------- ### GET /users Source: https://apifairy.readthedocs.io/en/latest/_sources/guide Retrieve a list of all users, with optional pagination. ```APIDOC ## GET /users ### Description Retrieve a list of all users, with optional pagination. ### Method GET ### Endpoint /users #### Query Parameters - **page** (integer) - Optional - The page number for pagination. - **per_page** (integer) - Optional - The number of items per page. ### Request Example ```json { "example": "No request body needed for GET request" } ``` ### Response #### Success Response (200) - **List of User objects** (array) - An array containing user objects. #### Response Example ```json { "users": [ { "id": 1, "username": "example_user_1", "url": "/users/1" }, { "id": 2, "username": "example_user_2", "url": "/users/2" } ], "pagination": { "page": 1, "per_page": 10, "total_pages": 5 } } ``` ``` -------------------------------- ### GET /users Source: https://apifairy.readthedocs.io/en/latest/guide Retrieves a list of users, with support for pagination. Query string parameters are documented using the @arguments decorator. ```APIDOC ## GET /users ### Description Retrieve all users. ### Method GET ### Endpoint /users ### Parameters #### Query Parameters - **pagination** (object) - Required - Pagination parameters (e.g., page, per_page). ### Request Example (No request body for GET request) ### Response #### Success Response (200) - **users_schema** (array) - A list of user objects. #### Response Example ```json [ { "id": 1, "url": "/users/1", "username": "john_doe" }, { "id": 2, "url": "/users/2", "username": "jane_doe" } ] ``` ``` -------------------------------- ### Document API Endpoint with Summary and Description Source: https://apifairy.readthedocs.io/en/latest/_sources/guide This example shows how to document an API endpoint with both a summary and a longer description in the view function's docstring. APIFairy uses this information to provide detailed documentation for the endpoint. Markdown is supported. ```python @users.route('/users', methods=['POST']) @body(user_schema) @response(user_schema, 201) def new(args): """Register a new user Clients can use this endpoint when they need to register a new user in the system. """ user = User(**args) db.session.add(user) db.session.commit() return user ``` -------------------------------- ### Documenting Query String Parameters (Python) Source: https://apifairy.readthedocs.io/en/latest/_sources/guide Example of using the `@arguments` decorator to automatically document query string parameters for an endpoint. It accepts a schema defining the expected arguments. ```python @users.route('/users', methods=['GET']) @arguments(pagination_schema) @response(users_schema) def get_users(pagination): """Retrieve all users""" # ... ``` -------------------------------- ### Documenting Marshmallow Schema Fields with Description (Python) Source: https://apifairy.readthedocs.io/en/latest/guide This Python example shows how to provide specific documentation for individual fields within a Marshmallow schema by using the `description` argument when declaring the field. This allows for detailed field-level documentation. ```python from marshmallow import Schema, fields, validate, ma # Assume User is defined elsewhere class User: pass class UserSchema(ma.SQLAlchemySchema): class Meta: model = User ordered = True id = ma.auto_field(dump_only=True, description="The user's id.") url = ma.String(dump_only=True, description="The user's unique URL.") username = ma.auto_field(required=True, validate=validate.Length(min=3, max=64), description="The user's username.") ``` -------------------------------- ### Documenting Path Parameters with typing.Annotated (Python 3.9+) Source: https://apifairy.readthedocs.io/en/latest/guide This example shows the preferred method for documenting path parameters using `typing.Annotated` in Python 3.9 and newer. It allows for type hints alongside documentation strings, avoiding linter errors. ```python from typing import Annotated from flask import Flask, abort from apifairy import response, authenticate, token_auth, schema app = Flask(__name__) # Assume User and db are defined elsewhere class User: pass db = type('obj', (object,), { 'session': type('obj', (object,), {'get': lambda self, cls, id: User() if id == 1 else None})() })() def authenticate(auth_func): def decorator(func): return func return decorator def response(schema): def decorator(func): return func return decorator users = type('obj', (object,), { 'route': lambda self, path, methods: lambda func: func } )() token_auth = None user_schema = None @users.route('/users/', methods=['GET']) @authenticate(token_auth) @response(user_schema) def get(id: Annotated[int, 'The id of the user to retrieve.']): """Retrieve a user by id""" return db.session.get(User, id) or abort(404) ``` -------------------------------- ### Webhook with POST Method and Blueprint Source: https://apifairy.readthedocs.io/en/latest/decorators Example of defining a webhook using the POST method and associating it with a blueprint. ```APIDOC ## Webhook with POST Method and Blueprint ### Description This example demonstrates how to define a webhook that uses the POST HTTP method and is associated with a specific blueprint named `users`. ### Method POST ### Endpoint Defined by the webhook function name or the `endpoint` argument. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body Documented using the `body` decorator. ### Request Example ```python from apifairy import webhook, body # Assuming 'users' is a defined blueprint object # from flask import Blueprint # users = Blueprint('users', __name__) @webhook(method='POST', blueprint=users) @body(ResultsSchema) def results(): pass ``` ### Response Documented using the `response` decorator. #### Success Response (200) Documented using the `response` decorator. #### Response Example ```json { "message": "Webhook processed successfully" } ``` ``` -------------------------------- ### Documenting Authentication with Docstrings Source: https://apifairy.readthedocs.io/en/latest/guide This example illustrates how to document authentication schemes by subclassing Flask-HTTPAuth and providing a docstring. APIFairy uses this docstring to generate the OpenAPI documentation for the specified authentication method. ```python from apifairy import authenticate, response, other_responses from flask_httpauth import HTTPBasicAuth class DocumentedAuth(HTTPBasicAuth): """Basic authentication scheme.""" pass basic_auth = DocumentedAuth() @tokens.route('/tokens', methods=['POST']) @authenticate(basic_auth) @response(token_schema) @other_responses({401: 'Invalid username or password'}) def new(): """Create new access and refresh tokens""" ... ``` -------------------------------- ### Documenting Both Query String and Headers with @arguments (Python) Source: https://apifairy.readthedocs.io/en/latest/guide This Python example demonstrates how to use the `@arguments` decorator multiple times in an APIFairy endpoint to document both query string parameters and request headers simultaneously. Each call to `@arguments` specifies a different schema and location. ```python from flask import Flask from apifairy import arguments, response from marshmallow import Schema, fields app = Flask(__name__) # Assume PaginationSchema and users_schema are defined elsewhere class PaginationSchema: pass class HeadersSchema(Schema): x_token = fields.String(required=True, data_key='X-Token') users_schema = None users = type('obj', (object,), { 'route': lambda self, path, methods: lambda func: func } )() @users.route('/users', methods=['GET']) @arguments(PaginationSchema) @arguments(HeadersSchema, location='headers') def all(pagination, headers): """Retrieve all users""" # ... pass ``` -------------------------------- ### GET /users (with Headers) Source: https://apifairy.readthedocs.io/en/latest/_sources/guide Retrieve a list of all users, requiring authentication via a request header. ```APIDOC ## GET /users (with Headers) ### Description Retrieve a list of all users, requiring authentication via a request header. ### Method GET ### Endpoint /users #### Request Headers - **X-Token** (string) - Required - Authentication token. ### Request Example ```json { "example": "No request body needed for GET request" } ``` ### Response #### Success Response (200) - **List of User objects** (array) - An array containing user objects. #### Response Example ```json { "users": [ { "id": 1, "username": "example_user_1", "url": "/users/1" } ] } ``` ``` -------------------------------- ### Adding Response Description (Python) Source: https://apifairy.readthedocs.io/en/latest/_sources/guide Example of adding a textual description to an endpoint's response using the `description` argument in the `@response` decorator. ```python @tokens.route('/tokens', methods=['PUT']) @body(token_schema) @response(token_schema, description='Newly issued access and refresh tokens') def refresh(args): """Refresh an access token""" ... ``` -------------------------------- ### GET /users/ Source: https://apifairy.readthedocs.io/en/latest/_sources/guide Retrieve a user by their unique identifier. ```APIDOC ## GET /users/ ### Description Retrieve a user by their unique identifier. ### Method GET ### Endpoint /users/ #### Path Parameters - **id** (int) - Required - The id of the user to retrieve. ### Request Example ```json { "example": "No request body needed for GET request" } ``` ### Response #### Success Response (200) - **User object** (object) - The retrieved user object. #### Response Example ```json { "id": 1, "username": "example_user", "url": "/users/1" } ``` ``` -------------------------------- ### Documenting API Responses with Headers Source: https://apifairy.readthedocs.io/en/latest/guide This example shows how to document response headers in addition to the response body. The `headers` argument in the `@response` decorator accepts a Marshmallow schema that defines the structure of the response headers, enhancing the OpenAPI documentation. ```python from apifairy import response, body import marshmallow as ma class HeadersSchema(ma.Schema): x_token = ma.String(data_key='X-Token') @tokens.route('/tokens', methods=['PUT']) @body(token_schema) @response(token_schema, headers=HeadersSchema) def refresh(args): """Refresh an access token""" ... ``` -------------------------------- ### GET /users/{id} Source: https://apifairy.readthedocs.io/en/latest/guide Retrieves a specific user by their ID. Path parameters can be documented using string annotations or typing.Annotated for Python 3.9+. ```APIDOC ## GET /users/{id} ### Description Retrieve a user by id. ### Method GET ### Endpoint /users/ ### Parameters #### Path Parameters - **id** (int) - Required - The id of the user to retrieve. ### Request Example (No request body for GET request) ### Response #### Success Response (200) - **User Schema** (object) - The user object. #### Response Example ```json { "id": 1, "url": "/users/1", "username": "john_doe" } ``` ``` -------------------------------- ### GET /users with Headers Source: https://apifairy.readthedocs.io/en/latest/guide Retrieves a list of users, requiring specific headers for authentication. Request headers can be documented using the @arguments decorator with location set to 'headers'. ```APIDOC ## GET /users (with Headers) ### Description Retrieve all users, authenticated with a token. ### Method GET ### Endpoint /users ### Parameters #### Query Parameters (No query parameters defined for this specific example) #### Request Headers - **X-Token** (string) - Required - Authentication token. ### Request Example (No request body for GET request) ### Response #### Success Response (200) - **users_schema** (array) - A list of user objects. #### Response Example ```json [ { "id": 1, "url": "/users/1", "username": "john_doe" }, { "id": 2, "url": "/users/2", "username": "jane_doe" } ] ``` ``` -------------------------------- ### Document Authentication with @authenticate and Subclasses (Python) Source: https://apifairy.readthedocs.io/en/latest/_sources/guide This example shows how to document authentication schemes using APIFairy's @authenticate decorator in conjunction with subclasses of Flask-HTTPAuth. By defining a subclass with a docstring, APIFairy can generate OpenAPI documentation for the authentication method. ```python from flask_httpauth import HTTPBasicAuth from apifairy import authenticate, response, other_responses class DocumentedAuth(HTTPBasicAuth): """Basic authentication scheme.""" pass basic_auth = DocumentedAuth() # Assuming tokens is a Flask blueprint or similar object # Assuming token_schema is defined elsewhere @tokens.route('/tokens', methods=['POST']) @authenticate(basic_auth) @response(token_schema) @other_responses({401: 'Invalid username or password'}) def new(args): """Create new access and refresh tokens""" ... ``` -------------------------------- ### Documenting Error Responses with Schemas Source: https://apifairy.readthedocs.io/en/latest/guide This example demonstrates documenting error responses with their corresponding schemas. By passing schema instances to the `@other_responses` decorator, the OpenAPI documentation will include the structure of error payloads for specific status codes. ```python from apifairy import response, body, other_responses @tokens.route('/tokens', methods=['PUT']) @body(token_schema) @response(token_schema, description='Newly issued access and refresh tokens') @other_responses({ 401: invalid_token_schema, 403: insufficient_permissions_schema }) def refresh(args): """Refresh an access token""" ... ``` -------------------------------- ### Example API Endpoint with APIFairy Decorators (Python) Source: https://apifairy.readthedocs.io/en/latest/_sources/intro This snippet demonstrates how to use APIFairy decorators to define an API endpoint for editing a post. It includes authentication, request body validation, response serialization, and handling of other possible responses. It relies on Flask-HTTPAuth and Flask-Marshmallow for authentication and schema definition, respectively. ```Python from apifairy import authenticate, body, response, other_responses # ... Assume token_auth, update_post_schema, post_schema, Post, db are defined elsewhere @posts_blueprint.route('/posts/', methods=['PUT']) @authenticate(token_auth) @body(update_post_schema) @response(post_schema) @other_responses({404: 'Post not found'}) def put(updated_post, id): """Edit a post.""" post = Post.query.get_or_404(id) for attr, value in updated_post.items(): setattr(post, attr, value) db.session.commit() return post ``` -------------------------------- ### Create User Endpoint with Multiple File Uploads Source: https://apifairy.readthedocs.io/en/latest/_sources/decorators This example demonstrates a Flask endpoint for creating a user that accepts multiple files. The @body decorator is configured with `location='form'` and `media_type='multipart/form-data'` to correctly parse multipart form data containing lists of files. ```python from apifairy import body @app.route('/users', methods=['POST']) @body(UserSchema, location='form', media_type='multipart/form-data') def create_user(user): # ... process user data and uploaded files ``` -------------------------------- ### Initialize APIFairy with Flask App (Python) Source: https://apifairy.readthedocs.io/en/latest/_sources/intro This code demonstrates the standard initialization of APIFairy as a Flask extension. It involves creating a Flask application instance and then passing this instance to the APIFairy constructor. ```Python from flask import Flask from apifairy import APIFairy app = Flask(__name__) apifairy = APIFairy(app) ``` -------------------------------- ### GET /users/ - Get User Source: https://apifairy.readthedocs.io/en/latest/decorators Retrieves a user by their ID and formats the response using the `@response` decorator. ```APIDOC ## GET /users/ ### Description Retrieves a specific user based on their ID. The response is serialized to JSON using the provided `UserSchema`. ### Method GET ### Endpoint /users/ ### Parameters #### Path Parameters - **id** (integer) - Required - The unique identifier of the user to retrieve. ### Response #### Success Response (200) - **user** (UserSchema) - The details of the requested user. #### Response Example ```json { "id": 1, "username": "john_doe", "email": "john.doe@example.com", "about_me": "A sample user." } ``` ``` -------------------------------- ### Initialize APIFairy with Flask App - Python Source: https://apifairy.readthedocs.io/en/latest/intro Initializes APIFairy as a standard Flask extension. This involves creating a Flask application instance and then passing it to the APIFairy constructor. The APIFairy instance can then be used to access API documentation endpoints. ```python from flask import Flask from apifairy import APIFairy app = Flask(__name__) apifairy = APIFairy(app) ``` -------------------------------- ### Get User by ID Source: https://apifairy.readthedocs.io/en/latest/_sources/decorators Retrieves a specific user by their ID. ```APIDOC ## GET /users/{id} ### Description Retrieves a specific user by their unique identifier. ### Method GET ### Endpoint /users/{id} ### Parameters #### Path Parameters - **id** (integer) - Required - The unique identifier of the user to retrieve. ### Response #### Success Response (200) - **id** (integer) - The unique identifier of the user. - **username** (string) - The username of the user. #### Response Example ```json { "id": 1, "username": "john_doe" } ``` #### Error Responses - **404**: User not found. - **400**: Invalid request. ``` -------------------------------- ### Documenting Both Query String and Headers (Python) Source: https://apifairy.readthedocs.io/en/latest/_sources/guide Shows how to use the `@arguments` decorator multiple times on a single endpoint to document both query string parameters and request headers. ```python @users.route('/users', methods=['GET']) @arguments(PaginationSchema) @arguments(HeadersSchema, location='headers') @response(users_schema) def all(pagination, headers): """Retrieve all users""" # ... ``` -------------------------------- ### Project Overview Documentation Source: https://apifairy.readthedocs.io/en/latest/guide Provide general project information, such as authentication details and error response structures, using module-level docstrings. ```APIDOC ## Project Overview Documentation ### Description Document general project information, including authentication and error response structures, using module-level docstrings in your Flask application's modules. APIFairy searches from the rightmost component of the application's import name. ### Method Module Docstring ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python """Welcome to My API Project! ## Project Overview This is the project overview. ## Authentication This is how authentication works. """ from flask import Flask from apifairy import APIFairy apifairy = APIFairy() def create_app(): app = Flask(__name__) app.config['APIFAIRY_TITLE'] = 'My API Project' app.config['APIFAIRY_VERSION'] = '1.0' apifairy.init_app(app) return app ``` ### Response #### Success Response (200) Documentation is attached to the project overview. #### Response Example N/A ``` -------------------------------- ### Get User with Authentication Source: https://apifairy.readthedocs.io/en/latest/_sources/decorators Retrieves a user, requiring basic HTTP authentication. ```APIDOC ## GET /users/{id} ### Description Retrieves a specific user by ID, requiring authentication. ### Method GET ### Endpoint /users/{id} ### Parameters #### Path Parameters - **id** (integer) - Required - The unique identifier of the user to retrieve. ### Authentication - Basic HTTP Authentication required. ### Response #### Success Response (200) - **id** (integer) - The unique identifier of the user. - **username** (string) - The username of the user. #### Response Example ```json { "id": 1, "username": "john_doe" } ``` ``` -------------------------------- ### Project Overview Documentation Source: https://apifairy.readthedocs.io/en/latest/_sources/guide Adding general project information like authentication and error response structures to your API documentation. ```APIDOC ## Project Overview Documentation ### Description Provide general project information for developers, such as authentication methods or error response structures, using module-level docstrings. APIFairy searches for this text in packages and modules referenced by the Flask application's import name. ### Method Module Docstring ### Endpoint N/A ### Parameters None ### Request Example ```python """Welcome to My API Project! ## Project Overview This is the project overview. ## Authentication This is how authentication works. """ from flask import Flask from apifairy import APIFairy apifairy = APIFairy() def create_app(): app = Flask(__name__) app.config['APIFAIRY_TITLE'] = 'My API Project' app.config['APIFAIRY_VERSION'] = '1.0' apifairy.init_app(app) return app ``` ### Response None ``` -------------------------------- ### Schema Description with Meta Class (Python) Source: https://apifairy.readthedocs.io/en/latest/_sources/guide Shows how to provide a general description for a Marshmallow schema by defining it within the inner `Meta` class using the `description` field. ```python class UserSchema(ma.SQLAlchemySchema): class Meta: model = User ordered = True description = 'This schema represents a user.' id = ma.auto_field(dump_only=True) url = ma.String(dump_only=True) username = ma.auto_field(required=True, validate=validate.Length(min=3, max=64)) ``` -------------------------------- ### Get User with Schematized Error Responses Source: https://apifairy.readthedocs.io/en/latest/_sources/decorators Retrieves a user, documenting specific schemas for error responses. ```APIDOC ## GET /users/{id} ### Description Retrieves a specific user by ID, with documented schemas for error responses. ### Method GET ### Endpoint /users/{id} ### Parameters #### Path Parameters - **id** (integer) - Required - The unique identifier of the user to retrieve. ### Response #### Success Response (200) - **id** (integer) - The unique identifier of the user. - **username** (string) - The username of the user. #### Response Example ```json { "id": 1, "username": "john_doe" } ``` #### Other Responses - **400**: BadRequestSchema - Invalid request. - **404**: UserNotFoundSchema - User not found. ``` -------------------------------- ### Add Project Overview in Module Docstring Source: https://apifairy.readthedocs.io/en/latest/_sources/guide Demonstrates how to add a project overview description using a module-level docstring in Python. APIFairy reads these docstrings to include general project information in the API documentation. Markdown formatting is supported for rich text. ```python """Welcome to My API Project! ## Project Overview This is the project overview. ## Authentication This is how authentication works. """ from flask import Flask from apifairy import APIFairy apifairy = APIFairy() def create_app(): app = Flask(__name__) app.config['APIFAIRY_TITLE'] = 'My API Project' app.config['APIFAIRY_VERSION'] = '1.0' apifairy.init_app(app) return app ``` -------------------------------- ### Project Configuration Source: https://apifairy.readthedocs.io/en/latest/_sources/guide Defines the title and version for your API project using Flask configuration. ```APIDOC ## Project Configuration ### Description Set the title and version of your API project in the Flask configuration object. ### Method Configuration ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from flask import Flask app = Flask(__name__) app.config['APIFAIRY_TITLE'] = 'My API Project' app.config['APIFAIRY_VERSION'] = '1.0' ``` ### Response None ``` -------------------------------- ### Get User with Schematized and Described Error Responses Source: https://apifairy.readthedocs.io/en/latest/_sources/decorators Retrieves a user, documenting schemas and descriptions for error responses. ```APIDOC ## GET /users/{id} ### Description Retrieves a specific user by ID, with documented schemas and descriptions for error responses. ### Method GET ### Endpoint /users/{id} ### Parameters #### Path Parameters - **id** (integer) - Required - The unique identifier of the user to retrieve. ### Response #### Success Response (200) - **id** (integer) - The unique identifier of the user. - **username** (string) - The username of the user. #### Response Example ```json { "id": 1, "username": "john_doe" } ``` #### Other Responses - **400**: (BadRequestSchema, 'Invalid request.') - **404**: (UserNotFoundSchema, 'User not found.') ``` -------------------------------- ### GET /users/ - Other Responses Source: https://apifairy.readthedocs.io/en/latest/decorators Specifies additional possible responses for an endpoint, typically for error conditions, with descriptions or schemas. ```APIDOC ## GET /users/ - Other Responses ### Description Retrieves a specific user and defines additional possible responses, such as for invalid requests or when a user is not found. ### Method GET ### Endpoint /users/ ### Parameters #### Path Parameters - **id** (integer) - Required - The unique identifier of the user to retrieve. ### Response #### Success Response (200) - **user** (UserSchema) - The details of the requested user. #### Error Responses - **400** (string) - Invalid request. - **404** (string) - User not found. #### Response Example (Success) ```json { "id": 1, "username": "john_doe", "email": "john.doe@example.com", "about_me": "A sample user." } ``` #### Response Example (404 Not Found) ```json { "message": "User not found." } ``` ``` -------------------------------- ### Get User with Multiple Error Responses Source: https://apifairy.readthedocs.io/en/latest/_sources/decorators Retrieves a user, with documentation for potential error responses like invalid request or user not found. ```APIDOC ## GET /users/{id} ### Description Retrieves a specific user by ID, documenting possible error responses. ### Method GET ### Endpoint /users/{id} ### Parameters #### Path Parameters - **id** (integer) - Required - The unique identifier of the user to retrieve. ### Response #### Success Response (200) - **id** (integer) - The unique identifier of the user. - **username** (string) - The username of the user. #### Response Example ```json { "id": 1, "username": "john_doe" } ``` #### Other Responses - **400**: Invalid request. - **404**: User not found. ``` -------------------------------- ### Path Parameter Documentation Source: https://apifairy.readthedocs.io/en/latest/_sources/guide Documenting path parameters for endpoints with dynamic URL components using annotations. ```APIDOC ## Path Parameter Documentation ### Description For endpoints with dynamic path components, APIFairy automatically extracts the parameter type from the Flask route. Provide a text description by adding a string as an annotation. ### Method GET ### Endpoint `/users/` ### Parameters #### Path Parameters - **user_id** (integer) - Required - The unique identifier of the user #### Query Parameters None #### Request Body None ### Request Example ```python @users.route('/users/', methods=['GET']) def get_user(user_id: "The unique identifier of the user"): # ... implementation ... pass ``` ### Response #### Success Response (200) - **user** (object) - The user object ``` -------------------------------- ### Initialize APIFairy with Flask App (Two-Phase) - Python Source: https://apifairy.readthedocs.io/en/latest/intro Demonstrates a two-phase initialization of APIFairy with a Flask application. This pattern is useful when the Flask app is created within a factory function. The APIFairy instance is created first and then initialized with the app later. ```python from flask import Flask from apifairy import APIFairy apifairy = APIFairy() def create_app(): app = Flask(__name__) apifairy.init_app(app) return app ``` -------------------------------- ### GET /users/ - Authenticated User Source: https://apifairy.readthedocs.io/en/latest/decorators Secures an endpoint using Flask-HTTPAuth, specifying authentication requirements and adding an Authentication section to the documentation. ```APIDOC ## GET /users/ - Authenticated User ### Description Retrieves a specific user, requiring authentication. The endpoint is secured using Flask-HTTPAuth, and the documentation includes an authentication section. ### Method GET ### Endpoint /users/ ### Parameters #### Path Parameters - **id** (integer) - Required - The unique identifier of the user to retrieve. ### Authentication - **Basic Auth** - Requires valid credentials. ### Response #### Success Response (200) - **user** (UserSchema) - The details of the requested user. #### Response Example ```json { "id": 1, "username": "john_doe", "email": "john.doe@example.com", "about_me": "A sample user." } ``` ``` -------------------------------- ### Authentication Documentation Source: https://apifairy.readthedocs.io/en/latest/guide Documenting authentication schemes using Flask-HTTPAuth. ```APIDOC ## POST /tokens (Authentication) ### Description Creates new access and refresh tokens using basic authentication. ### Method POST ### Endpoint /tokens ### Parameters #### Authentication - **Basic Auth** - Basic authentication scheme. ### Request Example (Requires Basic Authentication Header) ### Response #### Success Response (200) - **token** (object) - Newly created access and refresh tokens. #### Error Response (401) - **message** (string) - Invalid username or password. #### Response Example ```json { "token": { "access_token": "new_access_token", "refresh_token": "new_refresh_token" } } ``` ``` -------------------------------- ### Documenting Marshmallow Schemas with Meta Description (Python) Source: https://apifairy.readthedocs.io/en/latest/guide This Python code illustrates how to add a general description to a Marshmallow schema using the `description` field within the `Meta` class. This description will be included in the API documentation. ```python from marshmallow import Schema, fields, validate, ma # Assume User is defined elsewhere class User: pass class UserSchema(ma.SQLAlchemySchema): class Meta: model = User ordered = True description = 'This schema represents a user.' id = ma.auto_field(dump_only=True) url = ma.String(dump_only=True) username = ma.auto_field(required=True, validate=validate.Length(min=3, max=64)) ``` -------------------------------- ### Document Multiple Other Responses with Schemas Source: https://apifairy.readthedocs.io/en/latest/_sources/decorators This example shows how to use the @other_responses decorator to document error responses using specific Marshmallow schemas. This provides a structured format for error details in the API documentation. ```python from apifairy import response, other_responses @app.route('/users/') @response(UserSchema) @other_responses({400: BadRequestSchema, 404: UserNotFoundSchema}) def get_user(id): # ... get user or raise appropriate error ``` -------------------------------- ### Apply Basic Authentication to an Endpoint Source: https://apifairy.readthedocs.io/en/latest/_sources/decorators This example shows how to secure a Flask endpoint using the @authenticate decorator with a Flask-HTTPAuth Basic authentication object. This decorator enforces authentication and adds an 'Authentication' section to the API documentation. ```python from flask_httpauth import HTTPBasicAuth from apifairy import authenticate, response auth = HTTPBasicAuth() @app.route('/users/') @authenticate(auth) @response(UserSchema) def get_user(id): return User.query.get_or_404(id) ``` -------------------------------- ### Endpoint Documentation (Summary and Description) Source: https://apifairy.readthedocs.io/en/latest/_sources/guide Documenting an API endpoint with both a summary and a more detailed description in its view function's docstring. ```APIDOC ## Endpoint Documentation (Summary and Description) ### Description Document an endpoint with a summary on the first line of the docstring and a detailed explanation on subsequent lines. ### Method POST ### Endpoint `/users` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **args** (object) - Required - Arguments for the new user ### Request Example ```python @users.route('/users', methods=['POST']) @body(user_schema) @response(user_schema, 201) def new(args): """Register a new user Clients can use this endpoint when they need to register a new user in the system. """ user = User(**args) db.session.add(user) db.session.commit() return user ``` ### Response #### Success Response (201) - **user_schema** (object) - The registered user object ``` -------------------------------- ### Documenting Path Parameters with String Annotations (Python) Source: https://apifairy.readthedocs.io/en/latest/guide This code demonstrates how to document path parameters in APIFairy endpoints using simple string annotations for parameters. This method is compatible with most recent Python versions. Linters may flag these as invalid, requiring a 'noqa' comment. ```python from flask import Flask, abort from apifairy import response, authenticate, token_auth, schema app = Flask(__name__) # Assume User and db are defined elsewhere class User: pass db = type('obj', (object,), { 'session': type('obj', (object,), {'get': lambda self, cls, id: User() if id == 1 else None})() })() def authenticate(auth_func): def decorator(func): return func return decorator def response(schema): def decorator(func): return func return decorator users = type('obj', (object,), { 'route': lambda self, path, methods: lambda func: func } )() token_auth = None user_schema = None @users.route('/users/', methods=['GET']) @authenticate(token_auth) @response(user_schema) def get(id: 'The id of the user to retrieve.'): # noqa: F722 """Retrieve a user by id""" return db.session.get(User, id) or abort(404) ``` -------------------------------- ### Endpoint Documentation (Summary Only) Source: https://apifairy.readthedocs.io/en/latest/_sources/guide Documenting an API endpoint with a concise summary line in its view function's docstring. ```APIDOC ## Endpoint Documentation (Summary Only) ### Description Document an endpoint by adding a docstring to its view function. The first line serves as a short summary. ### Method POST ### Endpoint `/users` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **args** (object) - Required - Arguments for the new user ### Request Example ```python @users.route('/users', methods=['POST']) @body(user_schema) @response(user_schema, 201) def new(args): """Register a new user""" user = User(**args) db.session.add(user) db.session.commit() return user ``` ### Response #### Success Response (201) - **user_schema** (object) - The registered user object ``` -------------------------------- ### Create User with Response Details Source: https://apifairy.readthedocs.io/en/latest/_sources/decorators Creates a new user and returns a detailed response including status code and description. ```APIDOC ## POST /users ### Description Creates a new user. Returns a 201 status code upon successful creation. ### Method POST ### Endpoint /users ### Parameters #### Request Body - **username** (string) - Required - The username for the new user. ### Request Example ```json { "username": "new_user" } ``` ### Response #### Success Response (201) - **id** (integer) - The unique identifier of the created user. - **username** (string) - The username of the created user. #### Response Example ```json { "id": 3, "username": "new_user" } ``` #### Description A user was created. ``` -------------------------------- ### Authentication Documentation with @authenticate Source: https://apifairy.readthedocs.io/en/latest/_sources/guide This section explains how to document authentication schemes using the @authenticate decorator and custom Flask-HTTPAuth subclasses. ```APIDOC ## POST /tokens ### Description Creates new access and refresh tokens using basic authentication. ### Method POST ### Endpoint /tokens ### Parameters #### Request Body - **token_schema** (object) - Required - Token schema for the request. ### Request Example ```json { "example": "request body" } ``` ### Response #### Success Response (200) - **token_schema** (object) - Newly issued access and refresh tokens #### Response Example ```json { "example": "response body" } ``` ### Authentication - **Scheme**: Basic Authentication - **Description**: Basic authentication scheme. ### Error Responses - **401**: Invalid username or password ### Additional Notes - Subclassing Flask-HTTPAuth and adding a docstring allows for documented authentication schemes. ``` -------------------------------- ### POST /users - Create User Source: https://apifairy.readthedocs.io/en/latest/decorators Creates a new user with a specified schema, response status code, and description. ```APIDOC ## POST /users - Create User ### Description Creates a new user. The request body is validated against `UserSchema`, and the response is formatted according to `UserSchema` with a status code of 201. ### Method POST ### Endpoint /users ### Parameters #### Request Body - **user** (UserSchema) - Required - The schema defining the user data to create. * `id` (integer) - Optional - User ID. * `username` (string) - Required - User's username. * `email` (string) - Required - User's email address. * `about_me` (string) - Optional - User's "about me" description, defaults to an empty string. ### Request Example ```json { "username": "jane_doe", "email": "jane.doe@example.com" } ``` ### Response #### Success Response (201) - **user** (UserSchema) - The newly created user object. #### Response Example ```json { "id": 2, "username": "jane_doe", "email": "jane.doe@example.com", "about_me": "" } ``` ``` -------------------------------- ### Document API Endpoint with Summary Source: https://apifairy.readthedocs.io/en/latest/_sources/guide This Python snippet illustrates how to document an API endpoint using a concise summary in the view function's docstring. This summary provides a brief description of the endpoint's purpose. ```python @users.route('/users', methods=['POST']) @body(user_schema) @response(user_schema, 201) def new(args): """Register a new user""" user = User(**args) db.session.add(user) db.session.commit() return user ``` -------------------------------- ### Specify Response Status Code and Description Source: https://apifairy.readthedocs.io/en/latest/_sources/decorators This example shows how to use the @response decorator to define a non-default HTTP status code (201) and provide a textual description for a successful POST request. This information is used for API documentation generation. ```python from apifairy import body, response @app.route('/users', methods=['POST']) @body(UserSchema) @response(UserSchema, status_code=201, description='A user was created.') def create_user(user): # ... create user and return response ``` -------------------------------- ### Documenting Parameters with typing.Annotated (Python 3.9+) Source: https://apifairy.readthedocs.io/en/latest/_sources/guide Illustrates the preferred method of documenting parameters using `typing.Annotated` for type hints and metadata (like documentation strings), compatible with Python 3.9 and newer. This avoids linting issues. ```python from typing import Annotated @users.route('/users/', methods=['GET']) @authenticate(token_auth) @response(user_schema) def get(id: Annotated[int, 'The id of the user to retrieve.']): """Retrieve a user by id""" return db.session.get(User, id) or abort(404) ``` -------------------------------- ### Create User Endpoint with Single File Upload Source: https://apifairy.readthedocs.io/en/latest/_sources/decorators This example shows a Flask endpoint for creating a user, utilizing the @body decorator with a UserSchema that includes a FileField. The `location='form'` argument specifies that the data, including the file, should be parsed from the request form. ```python from apifairy import body @app.route('/users', methods=['POST']) @body(UserSchema, location='form') def create_user(user): # ... process user data and uploaded file ``` -------------------------------- ### User Schema Documentation Source: https://apifairy.readthedocs.io/en/latest/_sources/guide Documentation for the UserSchema, detailing its fields and their properties. ```APIDOC ## User Schema ### Description This schema represents a user. ### Fields - **id** (integer) - Read-only - The user's id. - **url** (string) - Read-only - The user's unique URL. - **username** (string) - Required - The user's username. Must be between 3 and 64 characters long. ``` -------------------------------- ### APIFairy Configuration Options Source: https://apifairy.readthedocs.io/en/latest/_sources/intro Configuration options for APIFairy, which are imported from the Flask configuration object. ```APIDOC ## Configuration Options ### APIFAIRY_TITLE - **Type**: String - **Default**: No title - **Description**: The API's title. ### APIFAIRY_VERSION - **Type**: String - **Default**: No version - **Description**: The API's version. ### APIFAIRY_APISPEC_PATH - **Type**: String - **Default**: `/apispec.json` - **Description**: The URL path where the JSON OpenAPI specification for this project is served. ### APIFAIRY_APISPEC_DECORATORS - **Type**: List - **Default**: `[]` - **Description**: A list of decorators to apply to the JSON OpenAPI endpoint. ### APIFAIRY_UI - **Type**: String - **Default**: `redoc` - **Description**: The documentation format to use. Supported formats are "redoc", "swagger_ui", "rapidoc" and "elements". ### APIFAIRY_UI_PATH - **Type**: String - **Default**: `/docs` - **Description**: The URL path where the documentation is served. ### APIFAIRY_UI_DECORATORS - **Type**: List - **Default**: `[]` - **Description**: A list of decorators to apply to the documentation endpoint. ### APIFAIRY_TAGS - **Type**: List - **Default**: `None` - **Description**: A list of tags to include in the documentation, in the desired order. ``` -------------------------------- ### Endpoint Documentation Source: https://apifairy.readthedocs.io/en/latest/guide Document individual API endpoints by adding docstrings to their corresponding view functions. The first line serves as a summary, and subsequent lines provide a detailed description. ```APIDOC ## Endpoint Documentation ### Description Document API endpoints using docstrings within their view functions. The first line acts as a summary, and the rest provides a detailed explanation. Docstrings can be written in Markdown. ### Method View Function Docstring ### Endpoint Variable (depends on @route decorator) ### Parameters #### Path Parameters None (defined in @route decorator) #### Query Parameters None (can be defined using other decorators like `@query_string`) #### Request Body None (can be defined using decorators like `@body`) ### Request Example ```python @users.route('/users', methods=['POST']) @body(user_schema) @response(user_schema, 201) def new(args): """Register a new user Clients can use this endpoint when they need to register a new user in the system. """ user = User(**args) db.session.add(user) db.session.commit() return user ``` ### Response #### Success Response (200) Response schema defined by `@response` decorator. #### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### Define POST Webhook with Blueprint in API Fairy Source: https://apifairy.readthedocs.io/en/latest/_sources/decorators This example illustrates defining a webhook with a specific HTTP method ('POST') and associating it with a blueprint ('users') using the `@webhook` decorator. The `@body` decorator is used to specify the request body schema. This helps in organizing webhooks alongside related API endpoints. ```python from apifairy import webhook, body @webhook(method='POST', blueprint=users) @body(ResultsSchema) def results(): pass ```