File size: 13,872 Bytes
32e4bbf |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 |
# Cloudflare Manager - API Reference
Complete reference for all classes and methods in the Cloudflare Manager.
## Table of Contents
1. [Classes](#classes)
- [CloudflareAccount](#cloudflareaccount)
- [CloudflareManager](#cloudflaremanager)
- [MultiAccountManager](#multiaccountmanager)
2. [Methods](#methods)
- [Pages Operations](#pages-operations)
- [Domain Operations](#domain-operations)
- [Zone Operations](#zone-operations)
- [Worker Operations](#worker-operations)
---
## Classes
### CloudflareAccount
Data class representing a Cloudflare account.
#### Constructor
```python
CloudflareAccount(email: str, token: str, account_id: Optional[str] = None, name: Optional[str] = None)
```
**Parameters:**
- `email` (str): Cloudflare account email
- `token` (str): API token with appropriate permissions
- `account_id` (Optional[str]): Account ID (auto-detected if not provided)
- `name` (Optional[str]): Account name for reference
**Example:**
```python
account = CloudflareAccount(
email="user@example.com",
token="your-api-token"
)
```
---
### CloudflareManager
Main class for interacting with Cloudflare API.
#### Constructor
```python
CloudflareManager(account: CloudflareAccount)
```
**Parameters:**
- `account` (CloudflareAccount): Account configuration
**Example:**
```python
account = CloudflareAccount(email="user@example.com", token="token")
cf = CloudflareManager(account)
```
---
### MultiAccountManager
Manager for handling multiple Cloudflare accounts.
#### Constructor
```python
MultiAccountManager()
```
#### Methods
##### add_account()
Add a Cloudflare account to the manager.
```python
add_account(name: str, email: str, token: str, account_id: Optional[str] = None) -> CloudflareManager
```
**Parameters:**
- `name` (str): Unique name for this account
- `email` (str): Cloudflare account email
- `token` (str): API token
- `account_id` (Optional[str]): Account ID
**Returns:** CloudflareManager instance
**Example:**
```python
manager = MultiAccountManager()
cf = manager.add_account("primary", "user@example.com", "token")
```
##### get_account()
Get a specific account manager by name.
```python
get_account(name: str) -> Optional[CloudflareManager]
```
**Parameters:**
- `name` (str): Account name
**Returns:** CloudflareManager instance or None
##### list_accounts()
List all configured account names.
```python
list_accounts() -> List[str]
```
**Returns:** List of account names
---
## Methods
### Pages Operations
#### create_pages_project()
Create a new Pages project.
```python
create_pages_project(project_name: str, production_branch: str = "main") -> Optional[Dict]
```
**Parameters:**
- `project_name` (str): Name of the Pages project
- `production_branch` (str): Git branch for production (default: "main")
**Returns:** Project details dict or None
**Example:**
```python
project = cf.create_pages_project("my-website", "main")
print(f"Project URL: https://{project['subdomain']}")
```
---
#### deploy_pages_project()
Deploy a Pages project from a local directory.
```python
deploy_pages_project(
project_name: str,
directory: str,
branch: str = "main",
commit_message: str = "Deploy via API"
) -> Optional[Dict]
```
**Parameters:**
- `project_name` (str): Name of the Pages project
- `directory` (str): Path to directory containing static files
- `branch` (str): Git branch name (default: "main")
- `commit_message` (str): Commit message for deployment
**Returns:** Deployment details dict or None
**Example:**
```python
deployment = cf.deploy_pages_project(
project_name="my-website",
directory="./dist",
branch="main",
commit_message="Deploy v1.0"
)
print(f"Deployed to: {deployment['url']}")
```
**Notes:**
- All files in the directory will be uploaded
- Maximum file size: 25MB per file
- Automatically generates manifest with SHA256 hashes
---
#### list_pages_projects()
List all Pages projects.
```python
list_pages_projects() -> List[Dict]
```
**Returns:** List of project dicts
**Example:**
```python
projects = cf.list_pages_projects()
for project in projects:
print(f"{project['name']}: {project['subdomain']}")
```
---
#### get_pages_project()
Get details of a specific Pages project.
```python
get_pages_project(project_name: str) -> Optional[Dict]
```
**Parameters:**
- `project_name` (str): Name of the project
**Returns:** Project details dict or None
---
#### list_pages_deployments()
List all deployments for a Pages project.
```python
list_pages_deployments(project_name: str) -> List[Dict]
```
**Parameters:**
- `project_name` (str): Name of the project
**Returns:** List of deployment dicts
**Example:**
```python
deployments = cf.list_pages_deployments("my-website")
for deployment in deployments:
print(f"Deployment: {deployment['id']} - {deployment['url']}")
```
---
### Domain Operations
#### add_pages_domain()
Add a custom domain to a Pages project.
```python
add_pages_domain(project_name: str, domain_name: str) -> Optional[Dict]
```
**Parameters:**
- `project_name` (str): Name of the Pages project
- `domain_name` (str): Domain to add (e.g., "example.com")
**Returns:** Domain details dict or None
**Example:**
```python
result = cf.add_pages_domain("my-website", "example.com")
print(f"Domain status: {result['status']}")
# Check if validation is needed
if result.get('validation_data'):
val = result['validation_data']
print(f"Add DNS record: {val['type']} {val['name']} = {val['value']}")
```
**Response Fields:**
- `name`: Domain name
- `status`: Status (e.g., "pending", "active")
- `validation_data`: DNS validation record (if needed)
- `type`: Record type (e.g., "TXT", "CNAME")
- `name`: Record name
- `value`: Record value
---
#### list_pages_domains()
List all domains for a Pages project.
```python
list_pages_domains(project_name: str) -> List[Dict]
```
**Parameters:**
- `project_name` (str): Name of the project
**Returns:** List of domain dicts
---
#### get_pages_domain()
Get details of a specific domain on a Pages project.
```python
get_pages_domain(project_name: str, domain_name: str) -> Optional[Dict]
```
**Parameters:**
- `project_name` (str): Name of the project
- `domain_name` (str): Domain name
**Returns:** Domain details dict or None
---
### Zone Operations
#### create_zone()
Create a new DNS zone (add domain to Cloudflare).
```python
create_zone(domain_name: str, zone_type: str = "full") -> Optional[Dict]
```
**Parameters:**
- `domain_name` (str): Domain name (e.g., "example.com")
- `zone_type` (str): Zone type (default: "full")
**Returns:** Zone details dict or None
**Example:**
```python
zone = cf.create_zone("example.com")
print(f"Zone ID: {zone['id']}")
print("Nameservers:")
for ns in zone['name_servers']:
print(f" {ns}")
```
**Response Fields:**
- `id`: Zone ID
- `name`: Domain name
- `status`: Zone status
- `name_servers`: List of Cloudflare nameservers
---
#### list_zones()
List all zones in the account.
```python
list_zones() -> List[Dict]
```
**Returns:** List of zone dicts
**Example:**
```python
zones = cf.list_zones()
for zone in zones:
print(f"{zone['name']} (ID: {zone['id']})")
```
---
#### get_zone()
Get details of a specific zone by ID.
```python
get_zone(zone_id: str) -> Optional[Dict]
```
**Parameters:**
- `zone_id` (str): Zone ID
**Returns:** Zone details dict or None
---
#### get_zone_by_name()
Get zone details by domain name.
```python
get_zone_by_name(domain_name: str) -> Optional[Dict]
```
**Parameters:**
- `domain_name` (str): Domain name
**Returns:** Zone details dict or None
**Example:**
```python
zone = cf.get_zone_by_name("example.com")
if zone:
print(f"Zone ID: {zone['id']}")
```
---
#### get_nameservers()
Get nameservers for a domain.
```python
get_nameservers(domain_name: str) -> Optional[List[str]]
```
**Parameters:**
- `domain_name` (str): Domain name
**Returns:** List of nameserver strings or None
**Example:**
```python
nameservers = cf.get_nameservers("example.com")
if nameservers:
print("Add these nameservers to your domain registrar:")
for ns in nameservers:
print(f" {ns}")
```
---
### Worker Operations
#### create_worker_route()
Create a worker route on a zone.
```python
create_worker_route(zone_id: str, pattern: str, script_name: str) -> Optional[Dict]
```
**Parameters:**
- `zone_id` (str): Zone ID
- `pattern` (str): Route pattern (e.g., "example.com/api/*")
- `script_name` (str): Worker script name
**Returns:** Route details dict or None
**Example:**
```python
route = cf.create_worker_route(
zone_id="zone-id-here",
pattern="example.com/api/*",
script_name="api-worker"
)
print(f"Route created: {route['id']}")
```
---
#### list_worker_routes()
List all worker routes for a zone.
```python
list_worker_routes(zone_id: str) -> List[Dict]
```
**Parameters:**
- `zone_id` (str): Zone ID
**Returns:** List of route dicts
**Example:**
```python
routes = cf.list_worker_routes("zone-id")
for route in routes:
print(f"{route['pattern']} -> {route['script']}")
```
---
#### delete_worker_route()
Delete a worker route.
```python
delete_worker_route(zone_id: str, route_id: str) -> bool
```
**Parameters:**
- `zone_id` (str): Zone ID
- `route_id` (str): Route ID
**Returns:** True if successful, False otherwise
---
#### upload_worker()
Upload a Worker script to Cloudflare.
```python
upload_worker(
script_name: str,
worker_file: str,
bindings: Optional[List[Dict]] = None
) -> Optional[Dict]
```
**Parameters:**
- `script_name` (str): Name of the worker script
- `worker_file` (str): Path to the worker .js file
- `bindings` (Optional[List[Dict]]): List of resource bindings (KV, R2, etc.)
**Returns:** Worker script details dict or None
**Example:**
```python
# Basic upload
result = cf.upload_worker(
script_name="my-worker",
worker_file="./worker.js"
)
# Upload with KV binding
result = cf.upload_worker(
script_name="my-worker",
worker_file="./worker.js",
bindings=[
{
"type": "kv_namespace",
"name": "MY_KV",
"namespace_id": "your-kv-id"
}
]
)
if result:
print(f"Worker uploaded: {result['id']}")
```
---
#### list_workers()
List all Worker scripts in the account.
```python
list_workers() -> List[Dict]
```
**Returns:** List of worker script dicts
**Example:**
```python
workers = cf.list_workers()
for worker in workers:
print(f"- {worker['id']} (modified: {worker['modified_on']})")
```
---
#### get_worker()
Get details about a specific Worker script.
```python
get_worker(script_name: str) -> Optional[Dict]
```
**Parameters:**
- `script_name` (str): Name of the worker script
**Returns:** Worker details dict or None
**Example:**
```python
worker = cf.get_worker("my-worker")
if worker:
print(f"Script ID: {worker['id']}")
print(f"Created: {worker['created_on']}")
```
---
#### delete_worker()
Delete a Worker script.
```python
delete_worker(script_name: str) -> bool
```
**Parameters:**
- `script_name` (str): Name of the worker script
**Returns:** True if successful, False otherwise
**Example:**
```python
if cf.delete_worker("old-worker"):
print("Worker deleted successfully")
```
---
#### add_worker_domain()
Add a custom domain to a worker.
```python
add_worker_domain(
hostname: str,
service: str,
zone_id: str,
environment: str = "production"
) -> Optional[Dict]
```
**Parameters:**
- `hostname` (str): Hostname (e.g., "api.example.com")
- `service` (str): Worker service name
- `zone_id` (str): Zone ID
- `environment` (str): Environment (default: "production")
**Returns:** Domain details dict or None
**Example:**
```python
result = cf.add_worker_domain(
hostname="api.example.com",
service="api-worker",
zone_id="zone-id",
environment="production"
)
```
---
#### list_worker_domains()
List all worker custom domains.
```python
list_worker_domains() -> List[Dict]
```
**Returns:** List of domain dicts
---
## Error Handling
All methods handle errors gracefully and return `None` or empty lists on failure. Errors are printed to stdout.
**Example:**
```python
project = cf.create_pages_project("test")
if project:
print("Success!")
else:
print("Failed - check error messages above")
```
## Response Format
All API methods return data in the format returned by Cloudflare's API. Common fields:
**Success Response:**
```json
{
"success": true,
"errors": [],
"messages": [],
"result": { ... }
}
```
**Error Response:**
```json
{
"success": false,
"errors": [
{
"code": 1234,
"message": "Error description"
}
],
"messages": [],
"result": null
}
```
## Rate Limits
Cloudflare API rate limits:
- **Standard**: 1,200 requests per 5 minutes
- **Varies by endpoint**
The manager automatically handles rate limit headers but doesn't implement retry logic.
## Authentication
All methods use Bearer token authentication via the `Authorization` header:
```
Authorization: Bearer YOUR_API_TOKEN
```
Make sure your API token has the necessary permissions for the operations you want to perform.
## Required Permissions
For full functionality, your API token should have:
- **Account Permissions:**
- Cloudflare Pages: Edit
- Workers Scripts: Edit
- **Zone Permissions:**
- DNS: Edit
- Workers Routes: Edit
- Zone: Edit
## Additional Resources
- [Cloudflare API Documentation](https://developers.cloudflare.com/api/)
- [Pages Documentation](https://developers.cloudflare.com/pages/)
- [Workers Documentation](https://developers.cloudflare.com/workers/)
- [DNS Documentation](https://developers.cloudflare.com/dns/)
## Version
**Current Version:** 1.0.0
**Python Compatibility:** Python 3.6+
**Dependencies:**
- requests >= 2.28.0
|