> ## Documentation Index
> Fetch the complete documentation index at: https://buttercms.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Python SDK

> The ButterCMS Python SDK provides a clean, Pythonic interface for Django, Flask, FastAPI, and vanilla Python applications.

## Installation

Install the SDK using pip:

```bash theme={null}
pip install buttercms-python
```

<Info>
  **Requirements:** Python 3.8 through 3.12 officially supported. Other Python 3.x versions may work but aren't guaranteed.
</Info>

## Initialization

Initialize the SDK with your Read API token from the [ButterCMS Settings](https://buttercms.com/settings/).

```python theme={null}
from butter_cms import ButterCMS

client = ButterCMS("your_api_token")
```

## API methods

All methods return Python dictionaries that can be accessed via standard dictionary syntax.

### Pages

Retrieve and search pages created in the ButterCMS dashboard.

```python theme={null}
# List all pages of a type
pages = client.pages.all("landing_page")

# List pages with parameters
pages = client.pages.all("landing_page", {
    "page": 1,
    "page_size": 10,
    "locale": "en",
    "preview": 1,      # Include draft content
    "levels": 2        # Depth of nested references
})

# Retrieve a single page
page = client.pages.get("landing_page", "home-page")

# Retrieve with parameters
page = client.pages.get("landing_page", "home-page", {
    "locale": "en",
    "preview": 1
})

# Search pages
results = client.pages.search("search query", {
    "page": 1,
    "page_size": 10
})
```

### Collections

Fetch content from Collections (structured data tables).

```python theme={null}
# Retrieve collection content
content = client.content_fields.get(["faq", "navigation"], {
    "locale": "en"
})

# Access collection data
faq_items = content["data"]["faq"]
nav_items = content["data"]["navigation"]
```

### Blog Posts

Access the built-in Blog Engine for posts, categories, tags, and authors.

```python theme={null}
# List blog posts
posts = client.posts.all({
    "page": 1,
    "page_size": 10,
    "exclude_body": "true"  # Exclude body for faster response
})

# Access post data
for post in posts["data"]:
    print(post["title"])

# Retrieve a single post
post = client.posts.get("my-post-slug")
print(post["data"]["title"])
print(post["data"]["body"])

# Search posts
results = client.posts.search("search query", {
    "page": 1,
    "page_size": 10
})
```

### Authors

```python theme={null}
# List all authors
authors = client.authors.all()

# Include recent posts for each author
authors = client.authors.all({
    "include": "recent_posts"
})

# Retrieve a single author
author = client.authors.get("jennifer-smith")

# With recent posts
author = client.authors.get("jennifer-smith", {
    "include": "recent_posts"
})
```

### Categories

```python theme={null}
# List all categories
categories = client.categories.all()

# Include recent posts for each category
categories = client.categories.all({
    "include": "recent_posts"
})

# Retrieve a single category
category = client.categories.get("news")

# With recent posts
category = client.categories.get("news", {
    "include": "recent_posts"
})
```

### Tags

```python theme={null}
# List all tags
tags = client.tags.all()

# Include recent posts for each tag
tags = client.tags.all({
    "include": "recent_posts"
})

# Retrieve a single tag
tag = client.tags.get("featured")

# With recent posts
tag = client.tags.get("featured", {
    "include": "recent_posts"
})
```

### Feeds

Retrieve RSS, Atom, and Sitemap feeds.

```python theme={null}
# Get RSS feed
rss = client.feeds.get("rss")

# Get Atom feed
atom = client.feeds.get("atom")

# Get Sitemap
sitemap = client.feeds.get("sitemap")
```

## Query parameters reference

| Parameter       | Applies To                | Description                           |
| --------------- | ------------------------- | ------------------------------------- |
| `page`          | Posts, Pages              | Page number for pagination            |
| `page_size`     | Posts, Pages              | Number of items per page              |
| `exclude_body`  | Posts                     | Exclude post body for faster response |
| `author_slug`   | Posts                     | Filter posts by author                |
| `category_slug` | Posts                     | Filter posts by category              |
| `tag_slug`      | Posts                     | Filter posts by tag                   |
| `include`       | Authors, Categories, Tags | Include `recent_posts` with response  |
| `locale`        | Pages, Collections        | Locale code for localized content     |
| `preview`       | Pages                     | Set to `1` to include draft content   |
| `levels`        | Pages                     | Depth of nested references (1–3)      |

## Complete example

```python theme={null}
from butter_cms import ButterCMS
import os

# Initialize client
client = ButterCMS(os.environ.get("BUTTERCMS_API_TOKEN"))

def fetch_homepage_data():
    """Fetch all data needed for the homepage."""
    try:
        # Fetch the home page
        page = client.pages.get("landing_page", "home", {
            "locale": "en"
        })

        # Fetch navigation from collection
        navigation = client.content_fields.get(["main_navigation"])

        # Fetch recent blog posts
        posts = client.posts.all({
            "page": 1,
            "page_size": 3,
            "exclude_body": "true"
        })

        return {
            "page": page.get("data"),
            "navigation": navigation.get("data", {}).get("main_navigation", []),
            "recent_posts": posts.get("data", [])
        }
    except Exception as e:
        print(f"Error fetching content: {e}")
        return None

# Usage
if __name__ == "__main__":
    data = fetch_homepage_data()
    if data:
        print(f"Page title: {data['page']['fields']['headline']}")
        print(f"Navigation items: {len(data['navigation'])}")
        print(f"Recent posts: {len(data['recent_posts'])}")
```

## Resources

<CardGroup cols={2}>
  <Card title="GitHub Repository" icon="github" href="https://github.com/ButterCMS/buttercms-python">
    View source code, report issues, and contribute
  </Card>

  <Card title="PyPI Package" icon="box" href="https://pypi.org/project/buttercms-python/">
    Package details and version history
  </Card>
</CardGroup>
