import os
import requests
zone_id = os.environ.get("ZONE_ID")
auth_token = os.environ.get("CLOUDFLARE_API_TOKEN")
url = f"https://api.cloudflare.com/client/v4/zones/{zone_id}/purge_cache"
headers = {
"Authorization": f"Bearer {auth_token}",
"Content-Type": "application/json"
}
data = {
"files": ["https://example.com/path/to/file.jpg"]
}
response = requests.post(url, headers=headers, json=data)
response.raise_for_status()
print(response.json())
import os
import httpx
zone_id = os.environ.get("ZONE_ID")
auth_token = os.environ.get("CLOUDFLARE_API_TOKEN")
url = f"https://api.cloudflare.com/client/v4/zones/{zone_id}/purge_cache"
headers = {
"Authorization": f"Bearer {auth_token}",
"Content-Type": "application/json"
}
data = {
"files": ["https://example.com/path/to/file.jpg"]
}
with httpx.Client() as client:
response = client.post(url, headers=headers, json=data)
response.raise_for_status()
print(response.json())
import fetch from 'node-fetch';
import process from 'process';
const zoneId = process.env.ZONE_ID;
const authToken = process.env.CLOUDFLARE_API_TOKEN;
const url = `https://api.cloudflare.com/client/v4/zones/${zoneId}/purge_cache`;
const headers = {
'Authorization': `Bearer ${authToken}`,
'Content-Type': 'application/json'
};
const data = {
files: ['https://example.com/path/to/file.jpg']
};
fetch(url, {
method: 'POST',
headers,
body: JSON.stringify(data)
})
.then(response => {
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
import axios from 'axios';
import process from 'process';
const zoneId = process.env.ZONE_ID;
const authToken = process.env.CLOUDFLARE_API_TOKEN;
const url = `https://api.cloudflare.com/client/v4/zones/${zoneId}/purge_cache`;
const headers = {
'Authorization': `Bearer ${authToken}`,
'Content-Type': 'application/json'
};
const data = {
files: ['https://example.com/path/to/file.jpg']
};
axios.post(url, data, { headers })
.then(response => {
console.log(response.data);
})
.catch(error => {
if (error.response) {
console.error('Error:', error.response.status, error.response.data);
} else {
console.error('Error:', error.message);
}
});
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"os"
)
func main() {
zoneID := os.Getenv("ZONE_ID")
authToken := os.Getenv("CLOUDFLARE_API_TOKEN")
url := fmt.Sprintf("https://api.cloudflare.com/client/v4/zones/%s/purge_cache", zoneID)
data := map[string]interface{}{
"files": []string{"https://example.com/path/to/file.jpg"},
}
jsonData, err := json.Marshal(data)
if err != nil {
log.Fatal(err)
}
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
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("Unexpected status code: %d", resp.StatusCode)
}
var result map[string]interface{}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
log.Fatal(err)
}
fmt.Println(result)
}
<?php
$zoneId = getenv('ZONE_ID');
$authToken = getenv('CLOUDFLARE_API_TOKEN');
$url = "https://api.cloudflare.com/client/v4/zones/{$zoneId}/purge_cache";
$data = [
'files' => ['https://example.com/path/to/file.jpg']
];
$options = [
'http' => [
'header' => [
"Authorization: Bearer {$authToken}",
"Content-Type: application/json"
],
'method' => 'POST',
'content' => json_encode($data)
]
];
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) {
throw new Exception("Request failed");
}
$response = json_decode($result, true);
print_r($response);
require 'net/http'
require 'json'
require 'uri'
zone_id = ENV['ZONE_ID']
auth_token = ENV['CLOUDFLARE_API_TOKEN']
uri = URI.parse("https://api.cloudflare.com/client/v4/zones/#{zone_id}/purge_cache")
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 = { files: ['https://example.com/path/to/file.jpg'] }.to_json
response = http.request(request)
unless response.is_a?(Net::HTTPSuccess)
raise "HTTP request failed: #{response.code} #{response.message}"
end
puts JSON.parse(response.body)
import Foundation
let zoneId = ProcessInfo.processInfo.environment["ZONE_ID"] ?? ""
let authToken = ProcessInfo.processInfo.environment["CLOUDFLARE_API_TOKEN"] ?? ""
let url = URL(string: "https://api.cloudflare.com/client/v4/zones/" + zoneId + "/purge_cache")!
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] = ["files": ["https://example.com/path/to/file.jpg"]]
request.httpBody = try JSONSerialization.data(withJSONObject: body)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error {
print("Error: \(error)")
return
}
guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
print("Unexpected status code: \((response as? HTTPURLResponse)?.statusCode ?? 0)")
return
}
if let data = data, let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
print(json)
}
}
task.resume()
RunLoop.main.run()
use std::collections::HashMap;
use std::env;
use reqwest::blocking::Client;
use reqwest::header;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let zone_id = env::var("ZONE_ID")?;
let auth_token = env::var("CLOUDFLARE_API_TOKEN")?;
let url = format!("https://api.cloudflare.com/client/v4/zones/{}/purge_cache", zone_id);
let client = Client::new();
let mut headers = header::HeaderMap::new();
headers.insert(
"Authorization",
format!("Bearer {}", auth_token).parse()?,
);
headers.insert("Content-Type", "application/json".parse()?);
let body: HashMap<&str, Vec<&str>> = HashMap::from([
("files", vec!["https://example.com/path/to/file.jpg"]),
]);
let response = client
.post(&url)
.headers(headers)
.json(&body)
.send()?;
if !response.status().is_success() {
return Err(format!("Request failed: {}", response.status()).into());
}
let json: serde_json::Value = response.json()?;
println!("{}", json);
Ok(())
}
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
var zoneId = Environment.GetEnvironmentVariable("ZONE_ID");
var authToken = Environment.GetEnvironmentVariable("CLOUDFLARE_API_TOKEN");
var client = new HttpClient();
var url = $"https://api.cloudflare.com/client/v4/zones/{zoneId}/purge_cache";
var request = new HttpRequestMessage(HttpMethod.Post, url);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authToken);
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var body = new Dictionary<string, object>
{
{ "files", new List<string> { "https://example.com/path/to/file.jpg" } }
};
request.Content = new StringContent(JsonSerializer.Serialize(body));
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}