{"id":7109,"library":"contentful","title":"Contentful Python SDK","description":"The Contentful Python SDK (`contentful.py`) is an actively maintained client library for the Contentful Content Delivery API (CDA). It enables Python applications to programmatically retrieve published content from Contentful spaces. Key features include content retrieval, synchronization, localization support, link resolution, and built-in rate-limiting recovery. The current stable version is 2.5.0.","status":"active","version":"2.5.0","language":"en","source_language":"en","source_url":"https://github.com/contentful/contentful.py","tags":["CMS","Contentful","API Client","Headless CMS"],"install":[{"cmd":"pip install contentful","lang":"bash","label":"Install stable version"}],"dependencies":[{"reason":"HTTP client for API communication.","package":"requests","optional":false},{"reason":"Date and time utilities, especially for parsing API date formats.","package":"python-dateutil","optional":false}],"imports":[{"note":"The Client class is typically imported directly from the top-level 'contentful' package, not from the internal 'contentful.client' module.","wrong":"import contentful; client = contentful.client.Client(...)","symbol":"Client","correct":"from contentful import Client"}],"quickstart":{"code":"import os\nfrom contentful import Client\n\nSPACE_ID = os.environ.get('CONTENTFUL_SPACE_ID', 'cfexampleapi') # Use example space for quick demo if not set\nACCESS_TOKEN = os.environ.get('CONTENTFUL_ACCESS_TOKEN', 'b4c0n73n7fu1') # Use example token for quick demo if not set\n\nif not SPACE_ID or not ACCESS_TOKEN:\n    print(\"Please set CONTENTFUL_SPACE_ID and CONTENTFUL_ACCESS_TOKEN environment variables.\")\nelse:\n    try:\n        client = Client(SPACE_ID, ACCESS_TOKEN)\n        entries = client.entries({'content_type': 'cat', 'limit': 1})\n\n        if entries:\n            first_cat = entries[0]\n            print(f\"Found entry: {first_cat.sys['id']}\")\n            print(f\"Name: {getattr(first_cat, 'name', 'N/A')}\")\n            if getattr(first_cat, 'image', None):\n                print(f\"Image URL: {first_cat.image.url()}\")\n        else:\n            print(\"No entries found for content type 'cat'.\")\n\n    except Exception as e:\n        print(f\"An error occurred: {e}\")","lang":"python","description":"This quickstart initializes the Contentful client using environment variables for credentials and fetches the first entry of content type 'cat'. Ensure you have `CONTENTFUL_SPACE_ID` and `CONTENTFUL_ACCESS_TOKEN` set, or it will fall back to a public example space."},"warnings":[{"fix":"Review any direct interactions with `ContentTypeCache` or internal SDK caching logic and update to use the new `space_id` parameter where applicable. Most users interacting only via the main `Client` should not be affected.","message":"Version 2.0.0 introduced breaking changes to the internal caching mechanism. The `__CACHE__` object type changed from `list` to `dict`, and the `ContentTypeCache.get` method now requires a `space_id` argument (e.g., `ContentTypeCache.get(space_id, content_type_id)`).","severity":"breaking","affected_versions":">=2.0.0"},{"fix":"Ensure your project runs on Python 3.9 or newer. If you were relying on `setup.py` for direct installation or `requirements.txt` for dependencies, these are no longer present in the source repository. Use `pip install contentful` as usual, or PDM if managing the project development directly.","message":"Starting with version 2.3.0, support for legacy Python versions was removed, requiring Python >= 3.9. Additionally, the project moved from `setup.py` and `requirements.txt` to `pyproject.toml` and PDM for dependency management.","severity":"breaking","affected_versions":">=2.3.0"},{"fix":"For new projects, always use `pip install contentful`. For existing projects using the old SDK, refer to the official documentation and migration guides for `contentful.py` as the API surface is different.","message":"This `contentful.py` SDK (for Content Delivery API) replaced an older, unofficial Python CDA SDK found at `https://github.com/contentful-labs/contentful.py`. Migrating from the older SDK requires code changes.","severity":"gotcha","affected_versions":"All versions (when migrating from old SDK)"},{"fix":"Always double-check that your `SPACE_ID` and `ACCESS_TOKEN` are correct for your Contentful space and the API you intend to use (Delivery API vs. Preview API). Ensure they are properly loaded from environment variables or a secure configuration.","message":"Incorrect `SPACE_ID` or `ACCESS_TOKEN` will result in `contentful.errors.UnauthorizedError`. This is a common setup mistake.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Implement client-side caching strategies for Contentful data, especially for frequently accessed content. Review application logic to minimize redundant API calls. The SDK will automatically retry, but persistent abuse will still fail.","message":"Contentful's API has rate limits. While the SDK includes built-in retry mechanisms, frequent or unoptimized queries can still lead to `contentful.errors.RateLimitExceededError`.","severity":"gotcha","affected_versions":"All versions"}],"env_vars":null,"last_verified":"2026-04-16T00:00:00.000Z","next_check":"2026-07-15T00:00:00.000Z","problems":[{"fix":"Verify that your `CONTENTFUL_SPACE_ID` and `CONTENTFUL_ACCESS_TOKEN` environment variables (or direct parameters to `Client`) exactly match the credentials from your Contentful space. Ensure the token is for the Content Delivery API (CDA) if accessing published content.","cause":"The provided `SPACE_ID` or `ACCESS_TOKEN` is incorrect, revoked, or does not have permissions for the requested action.","error":"contentful.errors.UnauthorizedError: The authorization token was invalid."},{"fix":"Review your application's API call patterns. Implement or improve caching mechanisms for Contentful data, especially for content that doesn't change frequently. Leverage the SDK's built-in retry logic but avoid aggressive polling.","cause":"Your application has made too many requests to the Contentful API within a short timeframe, exceeding the allowed rate limit.","error":"contentful.errors.RateLimitExceededError: Rate limit exceeded. Too many requests."},{"fix":"Double-check the IDs and query parameters you are using against your Contentful space's content model and entries. Ensure the content is published if you are using the Delivery API.","cause":"The `entry_id`, `content_type` ID, or other query parameters used to fetch content do not correspond to an existing resource in your Contentful space.","error":"contentful.errors.EntryNotFoundError: The requested resource or endpoint could not be found."},{"fix":"Upgrade to `contentful>=2.5.0` which fixed this issue. If upgrading is not possible, manually process `entry.raw` to extract only primitive types or use `entry.fields()` to access coerced field values.","cause":"Prior to `contentful>=2.5.0`, direct `json.dumps(entry.raw)` or similar serialization of `entry.raw` could fail if `entry.raw` contained unresolved `Entry` or `Link` objects.","error":"TypeError: Object of type Link is not JSON serializable"},{"fix":"When querying for an entry that has linked references, use the `include` parameter to specify the depth of link resolution. For example: `client.entry('my_entry_id', {'include': 2})`. The value of `include` should be greater than 0, up to a maximum of 10.","cause":"You are attempting to access fields (e.g., `entry.fields.author.fields.name`) on a linked entry that has not been resolved (fetched with `include` parameter). By default, linked entries are returned as `Link` objects, not full `Entry` objects.","error":"AttributeError: 'Link' object has no attribute 'fields'"}]}