Skip to content

papi.core.models

AppConfig

Bases: BaseModel

Top-level application configuration schema.

Groups all subcomponents of the configuration under named sections.

Attributes:

Name Type Description
logger LoggerConfig

Logging configuration.

info GeneralInfoConfig

General metadata.

server ServerConfig

Server options.

database DatabaseConfig

Connection strings for databases.

addons AddonsConfig

Plugin system configuration.

storage StorageConfig

Paths for file/image storage.

Example
AppConfig(
    logger=LoggerConfig(level="INFO"),
    info=GeneralInfoConfig(title="My API"),
    server=ServerConfig(host="0.0.0.0", port=8080),
    database=DatabaseConfig(sql_uri="sqlite:///./db.sqlite"),
    addons=AddonsConfig(extra_addons_path="./addons", enabled=[]),
    storage=StorageConfig(files="/data/files"),
)
Source code in papi/core/models/config.py
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
class AppConfig(BaseModel):
    """
    Top-level application configuration schema.

    Groups all subcomponents of the configuration under named sections.

    Attributes:
        logger (LoggerConfig): Logging configuration.
        info (GeneralInfoConfig): General metadata.
        server (ServerConfig): Server options.
        database (DatabaseConfig): Connection strings for databases.
        addons (AddonsConfig): Plugin system configuration.
        storage (StorageConfig): Paths for file/image storage.

    Example:
        ```python
        AppConfig(
            logger=LoggerConfig(level="INFO"),
            info=GeneralInfoConfig(title="My API"),
            server=ServerConfig(host="0.0.0.0", port=8080),
            database=DatabaseConfig(sql_uri="sqlite:///./db.sqlite"),
            addons=AddonsConfig(extra_addons_path="./addons", enabled=[]),
            storage=StorageConfig(files="/data/files"),
        )
        ```
    """

    logger: LoggerConfig
    info: FastAPIAppConfig
    server: UvicornServerConfig
    addons: AddonsConfig
    database: DatabaseConfig | None = None
    storage: StorageConfig | None = None

FastAPIAppConfig

Bases: BaseModel

Configuration model for FastAPI application metadata and settings.

This model defines metadata and behavioral options that are passed to the FastAPI constructor. It supports OpenAPI documentation configuration, middleware injection, server settings, and more.

Attributes:

Name Type Description
title Optional[str]

The title of the application, displayed in API docs and UIs.

summary Optional[str]

A short summary of the application.

description Optional[str]

A detailed description of the application, shown in docs.

terms_of_service Optional[str]

A URL to the terms of service for the API.

license_info Optional[Dict[str, Union[str, Any]]]

A dictionary specifying the license of the API.

contact Optional[Dict[str, Union[str, Any]]]

Contact information for the API maintainer.

version Optional[str]

The application version string.

middleware Optional[Sequence[str]]

A list of middleware identifiers to include in the app.

servers Optional[List[Dict[str, Union[str, Any]]]]

A list of server configurations for OpenAPI docs.

root_path Optional[str]

The root path where the app is mounted.

root_path_in_servers Optional[bool]

Whether to include the root path in OpenAPI server URLs.

openapi_url Optional[str]

The path where the OpenAPI schema will be served. Set to None to disable.

openapi_tags Optional[List[Dict[str, Any]]]

A list of tag definitions for organizing endpoints.

docs_url Optional[str]

The path to serve Swagger UI documentation. Set to None to disable.

redoc_url Optional[str]

The path to serve ReDoc documentation. Set to None to disable.

swagger_ui_parameters Optional[Dict[str, Any]]

Additional parameters to customize Swagger UI.

Notes
  • Extra fields are allowed and will be preserved.
  • Use the defined_fields() method to get only explicitly configured values.
Example
config = FastAPIAppConfig(title="My API", version="1.0.0")
fastapi_app = FastAPI(**config.defined_fields())
Source code in papi/core/models/config.py
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
class FastAPIAppConfig(BaseModel):
    """
    Configuration model for FastAPI application metadata and settings.

    This model defines metadata and behavioral options that are passed to the FastAPI constructor.
    It supports OpenAPI documentation configuration, middleware injection, server settings, and more.

    Attributes:
        title (Optional[str]): The title of the application, displayed in API docs and UIs.
        summary (Optional[str]): A short summary of the application.
        description (Optional[str]): A detailed description of the application, shown in docs.
        terms_of_service (Optional[str]): A URL to the terms of service for the API.
        license_info (Optional[Dict[str, Union[str, Any]]]): A dictionary specifying the license of the API.
        contact (Optional[Dict[str, Union[str, Any]]]): Contact information for the API maintainer.
        version (Optional[str]): The application version string.

        middleware (Optional[Sequence[str]]): A list of middleware identifiers to include in the app.

        servers (Optional[List[Dict[str, Union[str, Any]]]]): A list of server configurations for OpenAPI docs.
        root_path (Optional[str]): The root path where the app is mounted.
        root_path_in_servers (Optional[bool]): Whether to include the root path in OpenAPI server URLs.

        openapi_url (Optional[str]): The path where the OpenAPI schema will be served. Set to None to disable.
        openapi_tags (Optional[List[Dict[str, Any]]]): A list of tag definitions for organizing endpoints.
        docs_url (Optional[str]): The path to serve Swagger UI documentation. Set to None to disable.
        redoc_url (Optional[str]): The path to serve ReDoc documentation. Set to None to disable.
        swagger_ui_parameters (Optional[Dict[str, Any]]): Additional parameters to customize Swagger UI.

    Notes:
        - Extra fields are allowed and will be preserved.
        - Use the `defined_fields()` method to get only explicitly configured values.

    Example:
        ```python
        config = FastAPIAppConfig(title="My API", version="1.0.0")
        fastapi_app = FastAPI(**config.defined_fields())
        ```
    """

    title: Optional[str] = "pAPI Platform"
    summary: Optional[str] = None
    description: Optional[str] = "pAPI core API Platform"
    terms_of_service: Optional[str] = None
    license_info: Optional[Dict[str, Union[str, Any]]] = None
    contact: Optional[Dict[str, Union[str, Any]]] = None
    version: Optional[str] = ""

    middleware: Optional[Sequence[str]] = []

    servers: Optional[List[Dict[str, Union[str, Any]]]] = None
    root_path: Optional[str] = None
    root_path_in_servers: Optional[bool] = None

    openapi_url: Optional[str] = None
    openapi_tags: Optional[List[Dict[str, Any]]] = None
    docs_url: Optional[str] = None
    redoc_url: Optional[str] = None
    swagger_ui_parameters: Optional[Dict[str, Any]] = None

    model_config = {
        "extra": "allow",
        "populate_by_name": True,
    }

    def defined_fields(self) -> Dict[str, Any]:
        """
        Returns a dictionary with only the fields that have been explicitly set by the user,
        excluding default values and unset or None fields.

        Useful when passing configuration to FastAPI or related tools.

        Returns:
            Dict[str, Any]: A dictionary of defined configuration fields.
        """
        return self.model_dump(
            exclude_unset=True,
            exclude_defaults=True,
            exclude_none=True,
        )

defined_fields()

Returns a dictionary with only the fields that have been explicitly set by the user, excluding default values and unset or None fields.

Useful when passing configuration to FastAPI or related tools.

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: A dictionary of defined configuration fields.

Source code in papi/core/models/config.py
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
def defined_fields(self) -> Dict[str, Any]:
    """
    Returns a dictionary with only the fields that have been explicitly set by the user,
    excluding default values and unset or None fields.

    Useful when passing configuration to FastAPI or related tools.

    Returns:
        Dict[str, Any]: A dictionary of defined configuration fields.
    """
    return self.model_dump(
        exclude_unset=True,
        exclude_defaults=True,
        exclude_none=True,
    )

UvicornServerConfig

Bases: BaseModel

Configuration model for Uvicorn server runtime.

This model encapsulates all server-level parameters that can be passed to uvicorn.run(). It supports fine-grained control over networking, protocol, concurrency, SSL, live-reload, and more.

Attributes:

Name Type Description
host str

The hostname or IP address where the server will bind.

port int

The TCP port where the server will listen (must be between 1 and 65535).

uds Optional[Union[str, Path]]

Unix domain socket path to bind instead of host/port.

fd Optional[int]

File descriptor to bind instead of host/port/uds.

loop str

Event loop implementation to use (e.g., "auto", "uvloop", "asyncio").

http Union[str, type]

HTTP protocol class or string identifier.

ws Union[str, type]

WebSocket protocol class or string identifier.

ws_max_size int

Maximum size for incoming WebSocket messages.

ws_max_queue int

Maximum number of messages allowed in receive queue.

ws_ping_interval Optional[float]

Interval in seconds to send ping frames.

ws_ping_timeout Optional[float]

Timeout for WebSocket pings.

ws_per_message_deflate bool

Enable per-message compression for WebSockets.

lifespan str

Lifespan handling mode: "auto", "on", or "off".

env_file Optional[Union[str, Path]]

Path to a .env file with environment variables.

interface str

Server interface type ("auto", "asgi3", "asgi2", or "wsgi").

reload bool

Enable auto-reload in development mode.

reload_dirs Optional[Union[str, List[str]]]

Directories to watch for reload.

reload_delay float

Delay in seconds before reloading after changes.

reload_includes Optional[Union[str, List[str]]]

Glob patterns to include in reload.

reload_excludes Optional[Union[str, List[str]]]

Glob patterns to exclude from reload.

workers Optional[int]

Number of worker processes to spawn.

proxy_headers bool

Trust proxy headers (e.g., X-Forwarded-For).

server_header bool

Send the Server header in responses.

date_header bool

Send the Date header in responses.

forwarded_allow_ips Optional[Union[str, List[str]]]

List or string of IPs allowed to set forwarded headers.

root_path str

Root path to mount the application under.

limit_concurrency Optional[int]

Maximum number of concurrent connections.

limit_max_requests Optional[int]

Maximum number of requests before a worker is restarted.

backlog int

Maximum number of pending connections.

timeout_keep_alive int

Keep-alive timeout in seconds.

timeout_notify int

Timeout to notify of graceful shutdown.

timeout_graceful_shutdown Optional[int]

Max time allowed for graceful shutdown.

ssl_keyfile Optional[Union[str, Path]]

Path to the SSL key file.

ssl_certfile Optional[Union[str, Path]]

Path to the SSL certificate file.

ssl_keyfile_password Optional[str]

Password for the SSL key file, if encrypted.

ssl_version int

SSL protocol version (e.g., ssl.PROTOCOL_TLS).

ssl_cert_reqs int

Whether client certificates are required.

ssl_ca_certs Optional[str]

Path to CA certificates file.

ssl_ciphers str

String of ciphers to use for SSL connections.

headers Optional[List[Tuple[str, str]]]

List of custom headers to add to responses.

h11_max_incomplete_event_size Optional[int]

Limit for HTTP/1.1 incomplete event size.

Notes
  • Extra fields are allowed and will be preserved.
  • Use the defined_fields() method to retrieve only explicitly set values.
Example
config = UvicornServerConfig(host="0.0.0.0", port=8080, reload=True)
uvicorn.run(app, **config.defined_fields())
Source code in papi/core/models/config.py
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
class UvicornServerConfig(BaseModel):
    """
    Configuration model for Uvicorn server runtime.

    This model encapsulates all server-level parameters that can be passed to `uvicorn.run()`.
    It supports fine-grained control over networking, protocol, concurrency,
    SSL, live-reload, and more.

    Attributes:
        host (str): The hostname or IP address where the server will bind.
        port (int): The TCP port where the server will listen (must be between 1 and 65535).
        uds (Optional[Union[str, Path]]): Unix domain socket path to bind instead of host/port.
        fd (Optional[int]): File descriptor to bind instead of host/port/uds.
        loop (str): Event loop implementation to use (e.g., "auto", "uvloop", "asyncio").
        http (Union[str, type]): HTTP protocol class or string identifier.
        ws (Union[str, type]): WebSocket protocol class or string identifier.
        ws_max_size (int): Maximum size for incoming WebSocket messages.
        ws_max_queue (int): Maximum number of messages allowed in receive queue.
        ws_ping_interval (Optional[float]): Interval in seconds to send ping frames.
        ws_ping_timeout (Optional[float]): Timeout for WebSocket pings.
        ws_per_message_deflate (bool): Enable per-message compression for WebSockets.
        lifespan (str): Lifespan handling mode: "auto", "on", or "off".
        env_file (Optional[Union[str, Path]]): Path to a `.env` file with environment variables.
        interface (str): Server interface type ("auto", "asgi3", "asgi2", or "wsgi").
        reload (bool): Enable auto-reload in development mode.
        reload_dirs (Optional[Union[str, List[str]]]): Directories to watch for reload.
        reload_delay (float): Delay in seconds before reloading after changes.
        reload_includes (Optional[Union[str, List[str]]]): Glob patterns to include in reload.
        reload_excludes (Optional[Union[str, List[str]]]): Glob patterns to exclude from reload.
        workers (Optional[int]): Number of worker processes to spawn.
        proxy_headers (bool): Trust proxy headers (e.g., `X-Forwarded-For`).
        server_header (bool): Send the `Server` header in responses.
        date_header (bool): Send the `Date` header in responses.
        forwarded_allow_ips (Optional[Union[str, List[str]]]): List or string of IPs allowed to set forwarded headers.
        root_path (str): Root path to mount the application under.
        limit_concurrency (Optional[int]): Maximum number of concurrent connections.
        limit_max_requests (Optional[int]): Maximum number of requests before a worker is restarted.
        backlog (int): Maximum number of pending connections.
        timeout_keep_alive (int): Keep-alive timeout in seconds.
        timeout_notify (int): Timeout to notify of graceful shutdown.
        timeout_graceful_shutdown (Optional[int]): Max time allowed for graceful shutdown.
        ssl_keyfile (Optional[Union[str, Path]]): Path to the SSL key file.
        ssl_certfile (Optional[Union[str, Path]]): Path to the SSL certificate file.
        ssl_keyfile_password (Optional[str]): Password for the SSL key file, if encrypted.
        ssl_version (int): SSL protocol version (e.g., `ssl.PROTOCOL_TLS`).
        ssl_cert_reqs (int): Whether client certificates are required.
        ssl_ca_certs (Optional[str]): Path to CA certificates file.
        ssl_ciphers (str): String of ciphers to use for SSL connections.
        headers (Optional[List[Tuple[str, str]]]): List of custom headers to add to responses.
        h11_max_incomplete_event_size (Optional[int]): Limit for HTTP/1.1 incomplete event size.

    Notes:
        - Extra fields are allowed and will be preserved.
        - Use the `defined_fields()` method to retrieve only explicitly set values.

    Example:
        ```python
        config = UvicornServerConfig(host="0.0.0.0", port=8080, reload=True)
        uvicorn.run(app, **config.defined_fields())
        ```
    """

    host: str = Field(
        default="127.0.0.1", description="Hostname or IP address to bind the server."
    )
    port: int = Field(
        default=8000,
        description="Port to bind the server (must be between 1 and 65535).",
    )

    uds: Optional[Union[str, Path]] = None
    fd: Optional[int] = None
    loop: str = "auto"
    http: Union[str, type] = "auto"
    ws: Union[str, type] = "auto"
    ws_max_size: int = 16 * 1024 * 1024
    ws_max_queue: int = 32
    ws_ping_interval: Optional[float] = 20.0
    ws_ping_timeout: Optional[float] = 20.0
    ws_per_message_deflate: bool = True
    lifespan: str = "auto"
    env_file: Optional[Union[str, Path]] = None
    access_log: bool = True
    use_colors: Optional[bool] = None
    interface: str = "auto"
    reload: bool = False
    reload_dirs: Optional[Union[str, List[str]]] = None
    reload_delay: float = 0.25
    reload_includes: Optional[Union[str, List[str]]] = None
    reload_excludes: Optional[Union[str, List[str]]] = None
    workers: Optional[int] = None
    proxy_headers: bool = True
    server_header: bool = True
    date_header: bool = True
    forwarded_allow_ips: Optional[Union[str, List[str]]] = None
    root_path: str = ""
    limit_concurrency: Optional[int] = None
    limit_max_requests: Optional[int] = None
    backlog: int = 2048
    timeout_keep_alive: int = 5
    timeout_notify: int = 30
    timeout_graceful_shutdown: Optional[int] = None
    ssl_keyfile: Optional[Union[str, Path]] = None
    ssl_certfile: Optional[Union[str, Path]] = None
    ssl_keyfile_password: Optional[str] = None
    ssl_version: int = ssl.PROTOCOL_TLS
    ssl_cert_reqs: int = ssl.CERT_NONE
    ssl_ca_certs: Optional[str] = None
    ssl_ciphers: str = "TLSv1"
    headers: Optional[List[Tuple[str, str]]] = None
    h11_max_incomplete_event_size: Optional[int] = None

    model_config = {
        "extra": "allow",
        "populate_by_name": True,
    }

    def defined_fields(self) -> dict:
        """
        Return only the fields explicitly defined by the user,
        excluding unset fields, defaults, and None values.

        Returns:
            dict: A dictionary with the explicitly set configuration fields.
        """
        return self.model_dump(
            exclude_unset=True,
            exclude_defaults=True,
            exclude_none=True,
        )

    @field_validator("port")
    def validate_port(cls, v: int) -> int:
        """Ensure that the port is within the valid range (1–65535)."""
        if not (1 <= v <= 65535):
            raise ValueError("Port must be between 1 and 65535")
        return v

defined_fields()

Return only the fields explicitly defined by the user, excluding unset fields, defaults, and None values.

Returns:

Name Type Description
dict dict

A dictionary with the explicitly set configuration fields.

Source code in papi/core/models/config.py
292
293
294
295
296
297
298
299
300
301
302
303
304
def defined_fields(self) -> dict:
    """
    Return only the fields explicitly defined by the user,
    excluding unset fields, defaults, and None values.

    Returns:
        dict: A dictionary with the explicitly set configuration fields.
    """
    return self.model_dump(
        exclude_unset=True,
        exclude_defaults=True,
        exclude_none=True,
    )

validate_port(v)

Ensure that the port is within the valid range (1–65535).

Source code in papi/core/models/config.py
306
307
308
309
310
311
@field_validator("port")
def validate_port(cls, v: int) -> int:
    """Ensure that the port is within the valid range (1–65535)."""
    if not (1 <= v <= 65535):
        raise ValueError("Port must be between 1 and 65535")
    return v

AddonsConfig

Bases: BaseModel

Configuration for the plugin/addon system.

Attributes:

Name Type Description
extra_addons_path str

Filesystem path to external addons.

enabled List[str]

List of enabled addon identifiers.

config Dict[str, Dict[str, Any]]

Custom configuration per addon.

Example
AddonsConfig(
    extra_addons_path="/opt/plugins",
    enabled=["image_storage", "auth"],
    config={"image_storage": {"quality": 90}, "auth": {"provider": "oauth2"}},
)
Source code in papi/core/models/config.py
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
class AddonsConfig(BaseModel):
    """
    Configuration for the plugin/addon system.

    Attributes:
        extra_addons_path (str): Filesystem path to external addons.
        enabled (List[str]): List of enabled addon identifiers.
        config (Dict[str, Dict[str, Any]]): Custom configuration per addon.

    Example:
        ```python
        AddonsConfig(
            extra_addons_path="/opt/plugins",
            enabled=["image_storage", "auth"],
            config={"image_storage": {"quality": 90}, "auth": {"provider": "oauth2"}},
        )
        ```
    """

    extra_addons_path: str = Field(..., description="Path to external addons directory")
    enabled: List[str] = Field(
        default_factory=list, description="List of enabled addons"
    )
    config: Dict[str, Dict[str, Any]] = Field(
        default_factory=dict, description="Addon-specific configuration dictionary"
    )

LoggerConfig

Bases: BaseModel

Logging configuration for the application.

Attributes:

Name Type Description
level Optional[LoggerLevel]

Logging level (INFO or DEBUG).

log_file Optional[str]

Optional path to a log file.

json_log Optional[bool]

Whether to output logs in JSON format.

Example
LoggerConfig(level="DEBUG", log_file="logs/app.log", json_log=True)
Source code in papi/core/models/config.py
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
class LoggerConfig(BaseModel):
    """
    Logging configuration for the application.

    Attributes:
        level (Optional[LoggerLevel]): Logging level (INFO or DEBUG).
        log_file (Optional[str]): Optional path to a log file.
        json_log (Optional[bool]): Whether to output logs in JSON format.

    Example:
        ```python
        LoggerConfig(level="DEBUG", log_file="logs/app.log", json_log=True)
        ```
    """

    level: Optional[LoggerLevel] = LoggerLevel.INFO
    log_file: Optional[str] = None
    json_log: Optional[bool] = False

DatabaseConfig

Bases: BaseModel

Connection URIs for supported databases.

Attributes:

Name Type Description
mongodb_uri Optional[str]

MongoDB connection string.

redis_uri Optional[str]

Redis connection string.

sql_uri Optional[str]

SQL database connection string (PostgreSQL, MySQL, or SQLite).

Extra fields are allowed and will be preserved.

Example
DatabaseConfig(
    mongodb_uri="mongodb://localhost:27017",
    redis_uri="redis://localhost:6379",
    sql_uri="postgresql+asyncpg://user:pass@localhost/dbname",
)
Source code in papi/core/models/config.py
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
class DatabaseConfig(BaseModel):
    """
    Connection URIs for supported databases.

    Attributes:
        mongodb_uri (Optional[str]): MongoDB connection string.
        redis_uri (Optional[str]): Redis connection string.
        sql_uri (Optional[str]): SQL database connection string (PostgreSQL, MySQL, or SQLite).

    Extra fields are allowed and will be preserved.

    Example:
        ```python
        DatabaseConfig(
            mongodb_uri="mongodb://localhost:27017",
            redis_uri="redis://localhost:6379",
            sql_uri="postgresql+asyncpg://user:pass@localhost/dbname",
        )
        ```
    """

    mongodb_uri: Optional[str] = Field(default="", description="MongoDB connection URI")
    redis_uri: Optional[str] = Field(default="", description="Redis connection URI")
    sql_uri: Optional[str] = Field(
        default="", description="SQL (PostgreSQL/MySQL/SQlite) connection URI"
    )

    class Config:
        extra = "allow"

StorageConfig

Bases: BaseModel

Configuration for storage backends.

Attributes:

Name Type Description
files Optional[str]

Base path or URI for file storage.

images Optional[str]

Base path or URI for image storage.

Extra fields are allowed and will be preserved.

Source code in papi/core/models/config.py
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class StorageConfig(BaseModel):
    """
    Configuration for storage backends.

    Attributes:
        files (Optional[str]): Base path or URI for file storage.
        images (Optional[str]): Base path or URI for image storage.

    Extra fields are allowed and will be preserved.
    """

    files: Optional[str] = ""
    images: Optional[str] = ""

    class Config:
        extra = "allow"

AddonManifest

Bases: BaseModel

Model representing the manifest file of a pAPI addon.

This model is used to load and validate the configuration defined in a YAML file for a specific addon.

Attributes:

Name Type Description
name str

The internal name of the addon (derived from the directory name).

title Optional[str]

Human-readable title of the addon. Defaults to "pAPI Addon".

version Optional[str]

Version number of the addon. Defaults to "0.1".

dependencies List[str]

List of required addon identifiers this addon depends on.

python_dependencies List[str]

List of Python package dependencies required by the addon.

authors Union[str, Sequence[str], None]

Author name or list of authors.

description Optional[str]

Optional addon description.

path Path

Filesystem path to the addon directory (excluded from serialization).

Properties

addon_id (str): The unique ID of the addon, derived from the folder name.

Class Methods

from_yaml(path: Path) -> AddonManifest: Load an addon manifest from a YAML file.

Example
from pathlib import Path

manifest = AddonManifest.from_yaml(Path("addons/image_storage/manifest.yaml"))
print(manifest.title)  # "pAPI Addon" or custom title
print(manifest.addon_id)  # "image_storage"
Source code in papi/core/models/addons.py
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
class AddonManifest(BaseModel):
    """
    Model representing the manifest file of a pAPI addon.

    This model is used to load and validate the configuration defined in a YAML file for a specific addon.

    Attributes:
        name (str): The internal name of the addon (derived from the directory name).
        title (Optional[str]): Human-readable title of the addon. Defaults to "pAPI Addon".
        version (Optional[str]): Version number of the addon. Defaults to "0.1".
        dependencies (List[str]): List of required addon identifiers this addon depends on.
        python_dependencies (List[str]): List of Python package dependencies required by the addon.
        authors (Union[str, Sequence[str], None]): Author name or list of authors.
        description (Optional[str]): Optional addon description.
        path (Path): Filesystem path to the addon directory (excluded from serialization).

    Properties:
        addon_id (str): The unique ID of the addon, derived from the folder name.

    Class Methods:
        from_yaml(path: Path) -> AddonManifest:
            Load an addon manifest from a YAML file.

    Example:
        ```python
        from pathlib import Path

        manifest = AddonManifest.from_yaml(Path("addons/image_storage/manifest.yaml"))
        print(manifest.title)  # "pAPI Addon" or custom title
        print(manifest.addon_id)  # "image_storage"
        ```
    """

    name: str
    title: str | None = "pAPI Addon"
    version: str | None = "0.1"
    dependencies: List[str] = Field(default_factory=list)
    python_dependencies: List[str] = Field(default_factory=list)
    authors: str | Sequence | None = None
    description: Optional[str] = None
    path: Path = Field(exclude=True)

    @property
    def addon_id(self) -> str:
        return self.path.parts[-1]

    @classmethod
    def from_yaml(cls, path: Path):
        """
        Load an `AddonManifest` from a YAML file.

        Args:
            path (Path): Path to the `manifest.yaml` file.

        Returns:
            AddonManifest: An instance of the manifest model populated with data from the file.

        Raises:
            yaml.YAMLError: If the YAML is invalid or cannot be parsed.

        Example:
            Example `manifest.yaml` content:

            ```yaml
            name: custom addon
            version: 0.0.1
            description: My Custom API
            author: My Self

            dependencies:
            - user_auth_system

            python_dependencies:
            - "requests>=2.28.0"
            ```

            Usage:

            ```python
            from pathlib import Path
            manifest = AddonManifest.from_yaml(Path("addons/custom_addon/manifest.yaml"))
            print(manifest.addon_id)  # custom_addon
            print(manifest.name)  # custom_addon
            print(manifest.version)  # 0.1
            print(manifest.dependencies)  # ['user_auth_system']
            print(manifest.python_dependencies)  # ['requests>=2.28.0']
            ```
        """
        with open(path, "r", encoding="utf-8") as f:
            data = yaml.safe_load(f) or {}

        addon_dir = path.parent
        data["name"] = addon_dir.name

        return cls(**data, path=addon_dir)

from_yaml(path) classmethod

Load an AddonManifest from a YAML file.

Parameters:

Name Type Description Default
path Path

Path to the manifest.yaml file.

required

Returns:

Name Type Description
AddonManifest

An instance of the manifest model populated with data from the file.

Raises:

Type Description
YAMLError

If the YAML is invalid or cannot be parsed.

Example

Example manifest.yaml content:

name: custom addon
version: 0.0.1
description: My Custom API
author: My Self

dependencies:
- user_auth_system

python_dependencies:
- "requests>=2.28.0"

Usage:

from pathlib import Path
manifest = AddonManifest.from_yaml(Path("addons/custom_addon/manifest.yaml"))
print(manifest.addon_id)  # custom_addon
print(manifest.name)  # custom_addon
print(manifest.version)  # 0.1
print(manifest.dependencies)  # ['user_auth_system']
print(manifest.python_dependencies)  # ['requests>=2.28.0']
Source code in papi/core/models/addons.py
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
@classmethod
def from_yaml(cls, path: Path):
    """
    Load an `AddonManifest` from a YAML file.

    Args:
        path (Path): Path to the `manifest.yaml` file.

    Returns:
        AddonManifest: An instance of the manifest model populated with data from the file.

    Raises:
        yaml.YAMLError: If the YAML is invalid or cannot be parsed.

    Example:
        Example `manifest.yaml` content:

        ```yaml
        name: custom addon
        version: 0.0.1
        description: My Custom API
        author: My Self

        dependencies:
        - user_auth_system

        python_dependencies:
        - "requests>=2.28.0"
        ```

        Usage:

        ```python
        from pathlib import Path
        manifest = AddonManifest.from_yaml(Path("addons/custom_addon/manifest.yaml"))
        print(manifest.addon_id)  # custom_addon
        print(manifest.name)  # custom_addon
        print(manifest.version)  # 0.1
        print(manifest.dependencies)  # ['user_auth_system']
        print(manifest.python_dependencies)  # ['requests>=2.28.0']
        ```
    """
    with open(path, "r", encoding="utf-8") as f:
        data = yaml.safe_load(f) or {}

    addon_dir = path.parent
    data["name"] = addon_dir.name

    return cls(**data, path=addon_dir)

Meta

Bases: BaseModel

Source code in papi/core/models/response.py
 9
10
11
class Meta(BaseModel):
    timestamp: str = Field(..., description="ISO 8601 timestamp of the response")
    requestId: str = Field(..., description="Unique request identifier")

APIError

Bases: BaseModel

Source code in papi/core/models/response.py
14
15
16
17
18
19
20
21
22
class APIError(BaseModel):
    status_code: int = Field(..., description="HTTP status code of the error")
    detail: Optional[Any] = Field(
        None, description="Additional details about the error"
    )
    message: str = Field(
        default="Internal server error", description="Human-readable error message"
    )
    code: str = Field(default="ERROR", description="Custom application error code")

APIResponse

Bases: BaseModel

Source code in papi/core/models/response.py
25
26
27
28
29
30
31
32
33
34
class APIResponse(BaseModel):
    success: bool = Field(
        ..., description="Indicates whether the request was successful"
    )
    message: Optional[str] = Field(None, description="Optional message for the client")
    data: Optional[Any] = Field(None, description="Returned data if success is True")
    error: Optional[APIError] = Field(
        None, description="Error information if success is False"
    )
    meta: Meta = Field(..., description="Metadata for the response")