<@U04S8PLJWMT> i am creating python connector with...
# ask-ai
o
@kapa.ai i am creating python connector with the cdk i have a stream with parent child relation lets say i have multiple children streams for the same parent for example: i have an endpoint to list all application and 2 sub streams that receives the app id from the apps list to fetch the apps users and the app details GET /apps GET /apps/<app_id>/users GET /apps/<app_id> i want to limit the requests as much as possible to not hit a rate limit. if i use the same list apps stream for both sub streams will it refetch the apps list or it has some sort of catching inorder to prevent re quering the same endpoint data?
k
Yes, Airbyte’s CDK provides a caching mechanism specifically for this use case. If you have multiple child streams (substreams) that depend on the same parent stream (e.g., both
/apps/<app_id>/users
and
/apps/<app_id>
depend on
/apps
), you can enable caching on the parent stream to avoid refetching the same data multiple times. To do this: 1. Enable caching on the parent stream by overriding the
use_cache
property to return
True
. 2. Inherit your child streams from
HttpSubStream
and set the parent stream accordingly. When caching is enabled, the parent stream’s data is written to a temporary file the first time it is fetched. Subsequent requests from any child stream will read from this cache instead of making another HTTP request, as long as the data is available in the cache. This prevents redundant API calls and helps you stay within rate limits. Example:
Copy code
python class Apps(HttpStream):     @property     def use_cache(self) -> bool:         return True  class AppUsers(HttpSubStream):     parent_stream_class = Apps     # implement path, etc.  class AppDetails(HttpSubStream):     parent_stream_class = Apps     # implement path, etc.
This setup ensures that both
AppUsers
and
AppDetails
will use the cached results from the
Apps
stream, minimizing the number of requests to
/apps
regardless of how many child streams you have. For more details, see the official documentation on [Nested Streams & Caching](https://docs.airbyte.com/platform/connector-development/cdk-python/http-streams#nested-streams--caching) and the related forum discussion confirming this behavior [here](https://discuss.airbyte.io/t/587)<source>https://docs.airbyte.com/platform/connector-development/cdk-python/http-streams#nested-streams--caching</source><source>https://discuss.airbyte.io/t/587</source>.
o
@kapa.ai i created it based on your instractions and it does work me locally but when i run the connector the stream doesn't running it stops after 1 seconds and doesn't fetch any record this is my class code
Copy code
from functools import cached_property
from typing import Any, Iterable, List, Mapping, Optional
import requests
import logging
from airbyte_cdk import HttpSubStream, SyncMode
from .users_stream import UsersStream
from .api_base_v2_stream import ApiBaseV2Stream

logger = logging.getLogger("airbyte")


class MfaUserDevicesStream(ApiBaseV2Stream, HttpSubStream):
    """
    Stream for getting enrolled MFA factors for OneLogin users.

    This stream fetches a list of authentication factors registered to a particular user
    for multifactor authentication (MFA).
    Reference: https://developers.onelogin.com/api-docs/2/multi-factor-authentication/enrolled-factors
    """

    def __init__(
        self,
        authenticator,
        domain: str,
        parent: UsersStream,
        check: bool = False,
    ):
        """
        Initialize the MFA user devices stream.

        Args:
            authenticator: OAuth2 authenticator for OneLogin API
            domain: OneLogin domain/subdomain
            user_id: The ID of the user to get MFA user devices for
            check: Whether this is being called during connection check
        """
        ApiBaseV2Stream.__init__(
            self, authenticator=authenticator, domain=domain, check=check
        )
        HttpSubStream.__init__(self, parent=parent, authenticator=authenticator)

    @cached_property
    def name(self) -> str:
        """
        Stream name.

        Returns:
            str: The name of the stream
        """
        return "mfa_user_devices"

    @property
    def primary_key(self) -> str:
        """
        The primary key for the stream.

        Returns:
            str: The primary key
        """
        return "device_id"

    @property
    def supports_incremental(self) -> bool:
        """
        The cursor field for the stream.

        Returns:
            str: The cursor field
        """
        return False

    @property
    def cursor_field(self) -> str:
        """
        The cursor field for the stream.
        """
        return "place_holder"

    def base_path(
        self,
        *,
        stream_state: Optional[Mapping[str, Any]] = None,
        stream_slice: Optional[Mapping[str, Any]] = None,
        next_page_token: Optional[Mapping[str, Any]] = None,
    ) -> str:
        """
        Return the API endpoint path for getting MFA user devices.

        Returns:
            str: The endpoint path with user_id
        """
        logger.info(f"mfa_user_devices stream_slice: {stream_slice}")
        if stream_slice is None:
            raise ValueError("stream_slice is required")

        parent_record = stream_slice["parent"]
        user_id = parent_record["id"]
        return f"mfa/users/{user_id}/devices"

    def parse_response(
        self,
        response: requests.Response,
        *,
        stream_state: Mapping[str, Any],
        stream_slice: Optional[Mapping[str, Any]] = None,
        next_page_token: Optional[Mapping[str, Any]] = None,
    ) -> Iterable[Mapping[str, Any]]:
        """
        Parse the OneLogin Get MFA User Devices API response.

        The response returns an array of MFA user device objects directly.

        Args:
            response: The HTTP response from OneLogin API
            stream_state: The current state of the stream
            stream_slice: The current slice of the stream
            next_page_token: The token for the next page

        Yields:
            Mapping[str, Any]: MFA user device information
        """
        if stream_slice is None:
            raise ValueError("stream_slice is required")

        json_response = response.json()

        for device in json_response:
            device_dict = dict(device)
            device_dict["user_id"] = stream_slice["parent"]["id"]
            yield device_dict
k
A message from kapa.ai
Based on your description and the code you provided, it looks like you are using Airbyte’s CDK substream pattern correctly. However, if your stream stops after 1 second and fetches no records, there are a few common issues to check, based on Airbyte documentation and community discussions: ### 1. Parent Stream Must Yield Records The substream (
MfaUserDevicesStream
) relies on the parent stream (
UsersStream
) to yield records. If the parent stream yields no records, the substream will not make any requests. Make sure your
UsersStream
is correctly implemented and actually returns user records. ### 2. Correct Use of
stream_slice
Your
base_path
method expects
stream_slice
to contain a
"parent"
key with a user record. This is the pattern used by
HttpSubStream
, which generates slices from the parent stream’s records. If your parent stream or the way you instantiate the substream does not follow this,
stream_slice
may be
None
or malformed, causing the stream to stop. ### 3. Check for Caching If you have enabled caching on the parent stream (by setting
use_cache = True
), ensure that the cache is being populated. If the parent stream is not being called at all, or if the cache is empty, the substream will have nothing to process. See [Nested Streams & Caching](https://docs.airbyte.com/platform/connector-development/cdk-python/http-streams#nested-streams--caching). ### 4. Substream Instantiation When instantiating your substream, make sure you are passing a valid, fully-initialized parent stream instance. The parent stream should be ready to yield records when called by the substream. ### 5. Debug Logging You already have a logger in place. Check the logs for messages from both the parent and child streams. If you see your log message from
base_path
but no records are fetched, it’s likely a parent stream or slicing issue. ### 6. Yield vs Return in
stream_slices
If you override
stream_slices
in your substream or parent, make sure you use
yield
(not
return
) to generate all slices. Accidentally using
return
will stop iteration after the first slice, which is a common pitfall (see [forum example](https://discuss.airbyte.io/t/3084)). --- Summary: The most likely cause is that your parent stream is not yielding any records, or the substream is not receiving the expected
stream_slice
structure. Double-check your parent stream’s implementation and ensure it is compatible with Airbyte’s substream pattern. If you need a reference implementation, see the [official substream tutorial](https://docs.airbyte.com/platform/connector-development/tutorials/custom-python-connector/reading-from-a-subresource). If you need more specific help, please share the relevant code for your
UsersStream
and how you instantiate both streams in your connector’s
streams()
method.
o
@kapa.ai this is my parent stream:
Copy code
from functools import cached_property
from typing import Any, Iterable, Mapping, Optional
import requests
from .api_base_v2_stream import ApiBaseV2Stream
from _shared import read_all_records_from_stream


class UsersStream(ApiBaseV2Stream):
    """
    Stream for listing OneLogin users.

    This stream fetches a paginated list of users in a OneLogin account.
    Reference: https://developers.onelogin.com/api-docs/2/users/list-users
    """

    @cached_property
    def name(self) -> str:
        """
        Stream name.

        Returns:
            str: The name of the stream
        """
        return "users"

    @property
    def primary_key(self) -> str:
        """
        The primary key for the stream.

        Returns:
            str: The primary key
        """
        return "id"

    @property
    def use_cache(self) -> bool:
        """
        Whether to use cache for the stream.

        Returns:
            bool: Whether to use cache
        """
        return True

    def base_path(
        self,
        *,
        stream_state: Optional[Mapping[str, Any]] = None,
        stream_slice: Optional[Mapping[str, Any]] = None,
        next_page_token: Optional[Mapping[str, Any]] = None,
    ) -> str:
        """
        Return the API endpoint path for listing users.

        Returns:
            str: The endpoint path
        """
        return "users"

    def parse_response(
        self,
        response: requests.Response,
        *,
        stream_state: Mapping[str, Any],
        stream_slice: Optional[Mapping[str, Any]] = None,
        next_page_token: Optional[Mapping[str, Any]] = None,
    ) -> Iterable[Mapping[str, Any]]:
        """
        Parse the OneLogin List Users API response.

        The response returns an array of user objects directly (not wrapped in a data field).

        Args:
            response: The HTTP response from OneLogin API
            stream_state: The current state of the stream
            stream_slice: The current slice of the stream
            next_page_token: The token for the next page

        Yields:
            Dict[str, Any]: User information
        """
        json_response = response.json()
        yield from json_response
this is by sub stream:
Copy code
from functools import cached_property
from typing import Any, Iterable, List, Mapping, Optional
import requests
import logging
from airbyte_cdk import HttpSubStream, SyncMode
from .users_stream import UsersStream
from .api_base_v2_stream import ApiBaseV2Stream

logger = logging.getLogger("airbyte")


class MfaUserDevicesStream(ApiBaseV2Stream, HttpSubStream):
    """
    Stream for getting enrolled MFA factors for OneLogin users.

    This stream fetches a list of authentication factors registered to a particular user
    for multifactor authentication (MFA).
    Reference: https://developers.onelogin.com/api-docs/2/multi-factor-authentication/enrolled-factors
    """

    def __init__(
        self,
        authenticator,
        domain: str,
        parent: UsersStream,
        check: bool = False,
    ):
        """
        Initialize the MFA user devices stream.

        Args:
            authenticator: OAuth2 authenticator for OneLogin API
            domain: OneLogin domain/subdomain
            user_id: The ID of the user to get MFA user devices for
            check: Whether this is being called during connection check
        """
        ApiBaseV2Stream.__init__(
            self, authenticator=authenticator, domain=domain, check=check
        )
        HttpSubStream.__init__(self, parent=parent, authenticator=authenticator)

    @cached_property
    def name(self) -> str:
        """
        Stream name.

        Returns:
            str: The name of the stream
        """
        return "mfa_user_devices"

    @property
    def primary_key(self) -> str:
        """
        The primary key for the stream.

        Returns:
            str: The primary key
        """
        return "device_id"

    @property
    def supports_incremental(self) -> bool:
        """
        The cursor field for the stream.

        Returns:
            str: The cursor field
        """
        return False

    @property
    def cursor_field(self) -> str:
        """
        The cursor field for the stream.
        """
        return "place_holder"

    def base_path(
        self,
        *,
        stream_state: Optional[Mapping[str, Any]] = None,
        stream_slice: Optional[Mapping[str, Any]] = None,
        next_page_token: Optional[Mapping[str, Any]] = None,
    ) -> str:
        """
        Return the API endpoint path for getting MFA user devices.

        Returns:
            str: The endpoint path with user_id
        """
        logger.info(f"mfa_user_devices stream_slice: {stream_slice}")
        if stream_slice is None:
            raise ValueError("stream_slice is required")

        parent_record = stream_slice["parent"]
        user_id = parent_record["id"]
        return f"mfa/users/{user_id}/devices"

    def parse_response(
        self,
        response: requests.Response,
        *,
        stream_state: Mapping[str, Any],
        stream_slice: Optional[Mapping[str, Any]] = None,
        next_page_token: Optional[Mapping[str, Any]] = None,
    ) -> Iterable[Mapping[str, Any]]:
        """
        Parse the OneLogin Get MFA User Devices API response.

        The response returns an array of MFA user device objects directly.

        Args:
            response: The HTTP response from OneLogin API
            stream_state: The current state of the stream
            stream_slice: The current slice of the stream
            next_page_token: The token for the next page

        Yields:
            Mapping[str, Any]: MFA user device information
        """
        if stream_slice is None:
            raise ValueError("stream_slice is required")

        json_response = response.json()

        for device in json_response:
            device_dict = dict(device)
            device_dict["user_id"] = stream_slice["parent"]["id"]
            yield device_dict
why it works locally but when i run it on airbyte connections the sub sctream doesn't return any records?
k
A message from kapa.ai
Based on your code and the Airbyte documentation, your approach to using a parent (
UsersStream
) and substream (
MfaUserDevicesStream
) is correct in principle. However, the issue where the substream works locally but not when run as an Airbyte connection is a common one, and the knowledge sources provide some important clues: ### Key Points to Check 1. Parent Stream Must Yield Records The substream will only run if the parent stream (
UsersStream
) yields records. If, for any reason, the parent stream does not return any users (e.g., due to authentication, configuration, or API issues), the substream will not be called. This is a common cause for substreams not returning any records in Airbyte connections, even if they work locally. 2. Correct Use of
stream_slice
The
HttpSubStream
expects the parent stream to yield records, and it will pass each parent record as a
stream_slice
to the substream. Your code expects
stream_slice["parent"]
to exist. If the parent stream is not yielding records, or if the substream is not being instantiated with the correct parent,
stream_slice
may be
None
or malformed, causing the substream to skip processing. 3. Caching You have enabled caching on the parent stream (
use_cache = True
). This is correct and should prevent redundant requests, but if the cache is not being populated (e.g., if the parent stream is not called at all), the substream will have nothing to process. The documentation confirms that caching is the right approach for this pattern, but it is only effective if the parent stream is working as expected [Nested Streams & Caching](https://docs.airbyte.com/platform/connector-development/cdk-python/http-streams#nested-streams--caching). 4. Airbyte Platform Differences Sometimes, local runs (e.g., via
check
or
spec
commands) behave differently from full syncs in the Airbyte platform, especially regarding configuration, authentication, or environment variables. Double-check that your connector is receiving the correct configuration and credentials when run in Airbyte. 5. Debugging Add logging to both the parent and substream to confirm that: - The parent stream is being called and is yielding records. - The substream is receiving the expected
stream_slice
values. ### Example from Knowledge Sources The [official documentation](https://docs.airbyte.com/platform/connector-development/tutorials/custom-python-connector/reading-from-a-subresource) and forum posts confirm that the substream pattern works as you have implemented, but emphasize that the parent stream must yield records for the substream to function. If the parent yields nothing, the substream will not run. > The substream (
HttpSubStream
) class implements a
stream_slices
which creates a generator of all parent records. In other words, your substream re-reads all the records from the parent stream to generate paths. To avoid re-requesting the records from the parent stream you can set a
use_cache = True
attribute on your parent stream. This will store the already read records from the parent stream in a cache which is kept for the sync duration. > [How does sync mode work with sub stream / nested stream?](https://discuss.airbyte.io/t/587) ### What to Do Next - Check the Airbyte logs for both streams to ensure the parent is yielding records. - Verify configuration and authentication in the Airbyte UI. - Add debug logs to confirm the flow of records from parent to substream. - Ensure the parent stream is included in the
streams()
method
of your connector and is properly instantiated. If after these checks the issue persists, please provide the logs from your Airbyte run for further diagnosis. The knowledge sources do not provide a more specific solution for your exact scenario, but the above steps are the recommended troubleshooting path based on Airbyte's documented behavior and community experience.