Skip to content

Base

Infisical Base Resource.

InfisicalResourceRequest

Bases: BaseModel

Base model for Infisical resource requests.

Attributes:

Name Type Description
workspace_id str

The ID of the workspace.

environment str

The environment name.

Source code in src/infisical/resources/base.py
class InfisicalResourceRequest(BaseModel):
    """Base model for Infisical resource requests.

    Attributes:
        workspace_id (str): The ID of the workspace.
        environment (str): The environment name.
    """

    model_config = ConfigDict(validate_by_name=True)
    workspace_id: str = Field(alias="workspaceId")
    environment: str = Field()

InfisicalAPI

Base class for Infisical API resources.

This class provides common functionality for all Infisical resources, such as formatting URLs, raising resource errors, and verifying required parameters. It is not meant to be used directly, but rather as a base class for the specific resource classes.

To implement a new resource, inherit from this class and implement the required methods. The base_uri attribute should be set to the base URI of the resource. The resource-specific methods should be named according to the names designated in https://infisical.com/docs/api-reference/overview/introduction. For example, the Retrieve GET request would have a method named retrieve. In the list below, we just use placeholder names for the functions, but the real functions should use the actual names from the API documentation.

The function signature should be defined as follows, which is dependent on the type of HTTP request:

  • GET: def get_method(self, arg1, arg2, **params: Unpack[QueryParams]) -> BaseModel
  • POST: def post_method(self, request_model: RequestModel) -> BaseModel
  • PUT: def put_method(self, request_model: RequestModel) -> BaseModel
  • PATCH: def patch_method(self, request_model: RequestModel) -> BaseModel
  • DELETE: def delete_method(self, request_model: RequestModel) -> BaseModel

The QueryParams should be a TypedDict that defines the query parameters for the specific API URI, the RequestModel should be a Pydantic BaseModel that defines the request body for the specific API URI which is generated by the model_dump method, and the return type should be a Pydantic BaseModel that defines the response body for the specific API URI.

Note

In the GET signature above, arg1 and arg2 represent path parameters within the URL, while params are the optional query parameters. If any of the query parameters are required, they should be added to the required_params list in the verify_required_params call inside the function.

Typical method implementation
def list_my_resources(self, name: str, **params: Unpack[ResourceQueryParams]) -> ResourceList:
    # Only log INFO once per request to avoid clutter
    self.logger.info("Listing resources with params %s", params)
    # Verify that the required parameters are present, typically the workspaceId and environment
    self.verify_required_params(required_params=["workspaceId", "environment"], params=params)
    # Format the URL with the resource name and parameters
    url = self._format_url(f"/{name}")
    # Create the request with the formatted URL and parameters
    request = self.client.create_request(
        method="get", url=url, params=params,
    )
    # Return `handle_request` from the client with the request and expected response model(s)
    return self.client.handle_request(request=request, expected_responses={"resources": ResourceList})
Source code in src/infisical/resources/base.py
class InfisicalAPI:
    """Base class for Infisical API resources.

    This class provides common functionality for all Infisical resources, such as formatting URLs,
    raising resource errors, and verifying required parameters. It is not meant to be used directly,
    but rather as a base class for the specific resource classes.

    To implement a new resource, inherit from this class and implement the required methods.
    The `base_uri` attribute should be set to the base URI of the resource. The resource-specific methods
    should be named according to the names designated in https://infisical.com/docs/api-reference/overview/introduction.
    For example, the `Retrieve` GET request would have a method named `retrieve`. In the list below, we just use
    placeholder names for the functions, but the real functions should use the actual names from the API documentation.

    The function signature should be defined as follows, which is dependent on the type of HTTP request:

    - GET: `def get_method(self, arg1, arg2, **params: Unpack[QueryParams]) -> BaseModel`
    - POST: `def post_method(self, request_model: RequestModel) -> BaseModel`
    - PUT: `def put_method(self, request_model: RequestModel) -> BaseModel`
    - PATCH: `def patch_method(self, request_model: RequestModel) -> BaseModel`
    - DELETE: `def delete_method(self, request_model: RequestModel) -> BaseModel`

    The `QueryParams` should be a `TypedDict` that defines the query parameters for the specific API URI, the
    `RequestModel` should be a Pydantic `BaseModel` that defines the request body for the specific API URI which is
    generated by the `model_dump` method, and the return type should be a Pydantic `BaseModel` that defines the
    response body for the specific API URI.

    !!! note

        In the GET signature above, `arg1` and `arg2` represent path parameters within the URL, while `params` are
        the optional query parameters. If any of the query parameters are required, they should be added to the
        `required_params` list in the `verify_required_params` call inside the function.

    Example: Typical method implementation
        ```python
        def list_my_resources(self, name: str, **params: Unpack[ResourceQueryParams]) -> ResourceList:
            # Only log INFO once per request to avoid clutter
            self.logger.info("Listing resources with params %s", params)
            # Verify that the required parameters are present, typically the workspaceId and environment
            self.verify_required_params(required_params=["workspaceId", "environment"], params=params)
            # Format the URL with the resource name and parameters
            url = self._format_url(f"/{name}")
            # Create the request with the formatted URL and parameters
            request = self.client.create_request(
                method="get", url=url, params=params,
            )
            # Return `handle_request` from the client with the request and expected response model(s)
            return self.client.handle_request(request=request, expected_responses={"resources": ResourceList})
        ```
    """

    base_uri: str
    deprecated: bool = False

    def __init__(self, client: SyncOrAsyncClient) -> None:
        """Initialize the resource with the client.

        Args:
            client (SyncOrAsyncClient): An initialized [InfisicalClient][src.infisical.clients.clients.] or
                [InfisicalAsyncClient][src.infisical.clients.clients.].
        """
        self.client = client
        self.logger = logging.getLogger(self.__class__.__name__)
        self.api_endpoint = f"{self.client.url.rstrip('/')}/api"

    def _format_url(self, uri: str) -> str:
        """Generate the full URL for the resource.

        Args:
            uri (str): The URI path to append to the base URI.
        """
        uri_path = f"{self.base_uri.strip('/')}/{uri.strip('/')}"
        self.logger.debug("Formatting URL with endpoint %s and uri %s", self.api_endpoint, uri_path)
        if self.deprecated:
            warnings.warn(
                f"API endpoint {uri_path} is deprecated and may be removed in future versions.",
                DeprecationWarning,
                stacklevel=1,
            )
        return f"{self.api_endpoint}/{uri_path}"

    def raise_resource_error(self, message: str) -> None:
        """Raise an error for the resource.

        Args:
            message (str): The error message to raise.

        Raises:
            InfisicalResourceError: Uses your provided `message`.
        """
        raise InfisicalResourceError(message)

    def verify_required_params(self, required_params: list[str], params: dict) -> None:
        """Verify that the required parameters are present.

        The `required_params` list should contain the names of the parameters from the method's
        `**params: Unpack[QueryParams]` argument. The `params` dictionary should contain all the optional
        query parameters passed to the method.

        Args:
            required_params (list[str]): List of required parameters.
            params (dict): Dictionary of parameters to verify.

        Raises:
            InfisicalResourceError: If any required parameters are missing.
        """
        self.logger.debug("Verifying params %s against required parameters: %s", params, required_params)
        missing_params = [param for param in required_params if param not in params]
        if missing_params:
            self.raise_resource_error(f"Missing required parameters: {', '.join(missing_params)}")

__init__

__init__(client: SyncOrAsyncClient) -> None

Initialize the resource with the client.

Parameters:

Name Type Description Default
client SyncOrAsyncClient required
Source code in src/infisical/resources/base.py
def __init__(self, client: SyncOrAsyncClient) -> None:
    """Initialize the resource with the client.

    Args:
        client (SyncOrAsyncClient): An initialized [InfisicalClient][src.infisical.clients.clients.] or
            [InfisicalAsyncClient][src.infisical.clients.clients.].
    """
    self.client = client
    self.logger = logging.getLogger(self.__class__.__name__)
    self.api_endpoint = f"{self.client.url.rstrip('/')}/api"

raise_resource_error

raise_resource_error(message: str) -> None

Raise an error for the resource.

Parameters:

Name Type Description Default
message str

The error message to raise.

required

Raises:

Type Description
InfisicalResourceError

Uses your provided message.

Source code in src/infisical/resources/base.py
def raise_resource_error(self, message: str) -> None:
    """Raise an error for the resource.

    Args:
        message (str): The error message to raise.

    Raises:
        InfisicalResourceError: Uses your provided `message`.
    """
    raise InfisicalResourceError(message)

verify_required_params

verify_required_params(required_params: list[str], params: dict) -> None

Verify that the required parameters are present.

The required_params list should contain the names of the parameters from the method's **params: Unpack[QueryParams] argument. The params dictionary should contain all the optional query parameters passed to the method.

Parameters:

Name Type Description Default
required_params list[str]

List of required parameters.

required
params dict

Dictionary of parameters to verify.

required

Raises:

Type Description
InfisicalResourceError

If any required parameters are missing.

Source code in src/infisical/resources/base.py
def verify_required_params(self, required_params: list[str], params: dict) -> None:
    """Verify that the required parameters are present.

    The `required_params` list should contain the names of the parameters from the method's
    `**params: Unpack[QueryParams]` argument. The `params` dictionary should contain all the optional
    query parameters passed to the method.

    Args:
        required_params (list[str]): List of required parameters.
        params (dict): Dictionary of parameters to verify.

    Raises:
        InfisicalResourceError: If any required parameters are missing.
    """
    self.logger.debug("Verifying params %s against required parameters: %s", params, required_params)
    missing_params = [param for param in required_params if param not in params]
    if missing_params:
        self.raise_resource_error(f"Missing required parameters: {', '.join(missing_params)}")