RepoCloudflare (Workers AI)Cloudflare (Workers AI)published Feb 5, 2024seen 5d

cloudflare/cloudflare-python

Python

Open original ↗

Captured source

source ↗
published Feb 5, 2024seen 5dcaptured 8hhttp 200method plain

cloudflare/cloudflare-python

Description: The official Python library for the Cloudflare API

Language: Python

License: Apache-2.0

Stars: 461

Forks: 127

Open issues: 25

Created: 2024-02-05T19:49:12Z

Pushed: 2026-06-10T21:38:31Z

Default branch: main

Fork: no

Archived: no

README:

Cloudflare Python API library

The Cloudflare Python library provides convenient access to the Cloudflare REST API from any Python 3.9+ application. The library includes type definitions for all request params and response fields, and offers both synchronous and asynchronous clients powered by httpx.

It is generated with Stainless.

MCP Server

Use the Cloudflare MCP Server to enable AI assistants to interact with this API, allowing them to explore endpoints, make test requests, and use documentation to help integrate this SDK into your application.

![Add to Cursor](https://cursor.com/en-US/install-mcp?name=cloudflare-mcp&config=eyJjb21tYW5kIjoibnB4IiwiYXJncyI6WyIteSIsImNsb3VkZmxhcmUtbWNwIl0sImVudiI6eyJDTE9VREZMQVJFX0FQSV9UT0tFTiI6IlNuM2xaSlRCWDZra2c3T2RjQlVBeE9POTYzR0VJeUdRcW5GVE9GWVkiLCJDTE9VREZMQVJFX0FQSV9LRVkiOiIxNDRjOWRlZmFjMDQ5NjljN2JmYWQ4ZWZhYThlYTE5NCIsIkNMT1VERkxBUkVfRU1BSUwiOiJ1c2VyQGV4YW1wbGUuY29tIiwiQ0xPVURGTEFSRV9BUElfVVNFUl9TRVJWSUNFX0tFWSI6InYxLjAtMTQ0YzlkZWZhYzA0OTY5YzdiZmFkOGVmLTYzMWE0MWQwMDNhMzJkMjVmZTg3ODA4MWVmMzY1YzQ5NTAzZjdmYWRhNjAwZGE5MzVlMjg1MWExYzczMjYwODRiODVjYmY2NDI5YzRiODU5ZGU4NDc1NzMxZGM5MmE5YzMyOTYzMWU2ZDU5ZTZjNzNkYTdiMTk4NDk3MTcyYjRjZWZlMDcxZDkwZDBmNWQyNzE5In19)

> Note: You may need to set environment variables in your MCP client.

Documentation

The REST API documentation can be found on developers.cloudflare.com. The full API of this library can be found in [api.md](api.md).

Installation

# install from PyPI
pip install cloudflare

Usage

The full API of this library can be found in [api.md](api.md).

import os
from cloudflare import Cloudflare

client = Cloudflare(
api_token=os.environ.get("CLOUDFLARE_API_TOKEN"), # This is the default and can be omitted
)

zone = client.zones.create(
account={"id": "023e105f4ecef8ad9ca31a8372d0c353"},
name="example.com",
type="full",
)
print(zone.id)

While you can provide a api_email keyword argument, we recommend using python-dotenv to add CLOUDFLARE_EMAIL="user@example.com" to your .env file so that your API Email is not stored in source control.

Async usage

Simply import AsyncCloudflare instead of Cloudflare and use await with each API call:

import os
import asyncio
from cloudflare import AsyncCloudflare

client = AsyncCloudflare(
api_token=os.environ.get("CLOUDFLARE_API_TOKEN"), # This is the default and can be omitted
)

async def main() -> None:
zone = await client.zones.create(
account={"id": "023e105f4ecef8ad9ca31a8372d0c353"},
name="example.com",
type="full",
)
print(zone.id)

asyncio.run(main())

Functionality between the synchronous and asynchronous clients is otherwise identical.

With aiohttp

By default, the async client uses httpx for HTTP requests. However, for improved concurrency performance you may also use aiohttp as the HTTP backend.

You can enable this by installing aiohttp:

# install from PyPI
pip install cloudflare[aiohttp]

Then you can enable it by instantiating the client with http_client=DefaultAioHttpClient():

import os
import asyncio
from cloudflare import DefaultAioHttpClient
from cloudflare import AsyncCloudflare

async def main() -> None:
async with AsyncCloudflare(
api_token=os.environ.get("CLOUDFLARE_API_TOKEN"), # This is the default and can be omitted
http_client=DefaultAioHttpClient(),
) as client:
zone = await client.zones.create(
account={"id": "023e105f4ecef8ad9ca31a8372d0c353"},
name="example.com",
type="full",
)
print(zone.id)

asyncio.run(main())

Using types

Nested request parameters are TypedDicts. Responses are Pydantic models which also provide helper methods for things like:

  • Serializing back into JSON, model.to_json()
  • Converting to a dictionary, model.to_dict()

Typed requests and responses provide autocomplete and documentation within your editor. If you would like to see type errors in VS Code to help catch bugs earlier, set python.analysis.typeCheckingMode to basic.

Pagination

List methods in the Cloudflare API are paginated.

This library provides auto-paginating iterators with each list response, so you do not have to request successive pages manually:

from cloudflare import Cloudflare

client = Cloudflare()

all_accounts = []
# Automatically fetches more pages as needed.
for account in client.accounts.list():
# Do something with account here
all_accounts.append(account)
print(all_accounts)

Or, asynchronously:

import asyncio
from cloudflare import AsyncCloudflare

client = AsyncCloudflare()

async def main() -> None:
all_accounts = []
# Iterate through items across all pages, issuing requests as needed.
async for account in client.accounts.list():
all_accounts.append(account)
print(all_accounts)

asyncio.run(main())

Alternatively, you can use the .has_next_page(), .next_page_info(), or .get_next_page() methods for more granular control working with pages:

first_page = await client.accounts.list()
if first_page.has_next_page():
print(f"will fetch next page using these details: {first_page.next_page_info()}")
next_page = await first_page.get_next_page()
print(f"number of items we just fetched: {len(next_page.result)}")

# Remove `await` for non-async usage.

Or just work directly with the returned data:

first_page = await client.accounts.list()
for account in first_page.result:
print(account.id)

# Remove `await` for non-async usage.

Nested params

Nested parameters are dictionaries, typed using TypedDict, for example:

from cloudflare import Cloudflare

client = Cloudflare()

zone = client.zones.create(
account={},
name="example.com",
)
print(zone.account)

File uploads

Request parameters that correspond to file uploads can be passed as bytes, or a `PathLike` instance or a tuple of `(filename,…

Excerpt shown — open the source for the full document.