import os
import requests
zone_id = os.environ["ZONE_ID"]
auth_token = os.environ["CF_API_TOKEN"]
response = requests.post(
f"https://api.cloudflare.com/client/v4/zones/{zone_id}/activation",
headers={
"Authorization": f"Bearer {auth_token}",
"Content-Type": "application/json"
},
json={"name": "example.com"}
)
if response.status_code != 200:
raise Exception(f"Request failed with status {response.status_code}: {response.text}")
print(response.json())
import os
import httpx
zone_id = os.environ["ZONE_ID"]
auth_token = os.environ["CF_API_TOKEN"]
async def activate_zone():
async with httpx.AsyncClient() as client:
response = await client.post(
f"https://api.cloudflare.com/client/v4/zones/{zone_id}/activation",
headers={
"Authorization": f"Bearer {auth_token}",
"Content-Type": "application/json"
},
json={"name": "example.com"}
)
response.raise_for_status()
return response.json()
# For synchronous usage:
# with httpx.Client() as client:
# response = client.post(...)
# response.raise_for_status()
const fetch = require('node-fetch');
const zoneId = process.env.ZONE_ID;
const authToken = process.env.CF_API_TOKEN;
(async () => {
try {
const response = await fetch(`https://api.cloudflare.com/client/v4/zones/${zoneId}/activation`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${authToken}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ name: 'example.com' })
});
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}: ${await response.text()}`);
}
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error:', error);
}
})();
const axios = require('axios');
const zoneId = process.env.ZONE_ID;
const authToken = process.env.CF_API_TOKEN;
(async () => {
try {
const response = await axios.post(
`https://api.cloudflare.com/client/v4/zones/${zoneId}/activation`,
{ name: 'example.com' },
{
headers: {
'Authorization': `Bearer ${authToken}`,
'Content-Type': 'application/json'
}
}
);
if (response.status !== 200) {
throw new Error(`Request failed with status ${response.status}: ${JSON.stringify(response.data)}`);
}
console.log(response.data);
} catch (error) {
console.error('Error:', error.message);
}
})();
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"os"
)
type RequestBody struct {
Name string `json:"name"`
}
func main() {
zoneId := os.Getenv("ZONE_ID")
authToken := os.Getenv("CF_API_TOKEN")
url := fmt.Sprintf("https://api.cloudflare.com/client/v4/zones/%s/activation", zoneId)
body := RequestBody{Name: "example.com"}
jsonBody, err := json.Marshal(body)
if err != nil {
log.Fatal(err)
}
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonBody))
if err != nil {
log.Fatal(err)
}
req.Header.Set("Authorization", "Bearer "+authToken)
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
log.Fatalf("Request failed with status %d: %s", resp.StatusCode, readBody(resp.Body))
}
var result map[string]interface{}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
log.Fatal(err)
}
fmt.Println(result)
}
func readBody(body io.ReadCloser) string {
data, _ := io.ReadAll(body)
return string(data)
}
<?php
$zoneId = getenv('ZONE_ID');
$authToken = getenv('CF_API_TOKEN');
$url = "https://api.cloudflare.com/client/v4/zones/{$zoneId}/activation";
$data = ['name' => 'example.com'];
$options = [
'http' => [
'header' => [
"Authorization: Bearer {$authToken}",
"Content-Type: application/json"
],
'method' => 'POST',
'content' => json_encode($data)
]
];
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
if ($http_response_header[0] !== 'HTTP/1.1 200 OK') {
throw new Exception("Request failed: " . $response);
}
$json = json_decode($response, true);
print_r($json);
require 'net/http'
require 'json'
require 'uri'
zone_id = ENV['ZONE_ID']
auth_token = ENV['CF_API_TOKEN']
uri = URI.parse("https://api.cloudflare.com/client/v4/zones/#{zone_id}/activation")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Post.new(uri.request_uri)
request['Authorization'] = "Bearer #{auth_token}"
request['Content-Type'] = 'application/json'
request.body = { name: 'example.com' }.to_json
response = http.request(request)
unless response.code == '200'
raise "Request failed with status #{response.code}: #{response.body}"
end
puts JSON.parse(response.body)
import Foundation
let zoneId = ProcessInfo.processInfo.environment["ZONE_ID"] ?? ""
let authToken = ProcessInfo.processInfo.environment["CF_API_TOKEN"] ?? ""
guard let url = URL(string: "https://api.cloudflare.com/client/v4/zones/" + zoneId + "/activation") else {
fatalError("Invalid URL")
}
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Bearer \(authToken)", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let body: [String: Any] = ["name": "example.com"]
request.httpBody = try? JSONSerialization.data(withJSONObject: body)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print("Error: \(error?.localizedDescription ?? "Unknown error")")
return
}
if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode != 200 {
print("Request failed with status \(httpResponse.statusCode): \(String(data: data, encoding: .utf8) ?? "")")
return
}
if let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
print(json)
}
}
task.resume()
// For synchronous execution in a playground or test:
// let (data, response) = try await URLSession.shared.data(for: request)
// if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 {
// let json = try JSONSerialization.jsonObject(with: data) as? [String: Any]
// print(json)
// }
use std::env;
use reqwest::blocking::Client;
use serde_json::json;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let zone_id = env::var("ZONE_ID")?;
let auth_token = env::var("CF_API_TOKEN")?;
let client = Client::new();
let url = format!("https://api.cloudflare.com/client/v4/zones/{}/activation", zone_id);
let response = client
.post(&url)
.header("Authorization", format!("Bearer {}", auth_token))
.header("Content-Type", "application/json")
.json(&json!({"name": "example.com"}))
.send()?;
if !response.status().is_success() {
return Err(format!("Request failed with status {}: {}", response.status(), response.text()?).into());
}
let json: serde_json::Value = response.json()?;
println!("{}", json);
Ok(())
}
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
var zoneId = Environment.GetEnvironmentVariable("ZONE_ID");
var authToken = Environment.GetEnvironmentVariable("CF_API_TOKEN");
using var client = new HttpClient();
client.BaseAddress = new Uri("https://api.cloudflare.com/client/v4/");
var request = new HttpRequestMessage(HttpMethod.Post, $"zones/{zoneId}/activation");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authToken);
request.Content = new StringContent(JsonSerializer.Serialize(new { name = "example.com" }), System.Text.Encoding.UTF8, "application/json");
var response = await client.SendAsync(request);
if (!response.IsSuccessStatusCode)
{
var errorContent = await response.Content.ReadAsStringAsync();
throw new Exception($"Request failed with status {response.StatusCode}: {errorContent}");
}
var json = await response.Content.ReadAsStringAsync();
Console.WriteLine(json);
}
}