import os
import requests
zone_id = os.environ["ZONE_ID"]
headers = {
"Authorization": f"Bearer {os.environ['CF_API_TOKEN']}",
"Content-Type": "application/json"
}
data = {
"type": "A",
"name": "example.com",
"content": "192.0.2.1",
"ttl": 300
}
response = requests.post(
f"https://api.cloudflare.com/client/v4/zones/{zone_id}/dns_records",
headers=headers,
json=data
)
response.raise_for_status()
print(response.json())
import os
import httpx
zone_id = os.environ["ZONE_ID"]
headers = {
"Authorization": f"Bearer {os.environ['CF_API_TOKEN']}",
"Content-Type": "application/json"
}
data = {
"type": "A",
"name": "example.com",
"content": "192.0.2.1",
"ttl": 300
}
with httpx.Client() as client:
response = client.post(
f"https://api.cloudflare.com/client/v4/zones/{zone_id}/dns_records",
headers=headers,
json=data
)
response.raise_for_status()
print(response.json())
import fetch from 'node-fetch';
import { env } from 'node:process';
const zoneId = env.ZONE_ID;
const apiToken = env.CF_API_TOKEN;
const headers = {
'Authorization': `Bearer ${apiToken}`,
'Content-Type': 'application/json'
};
const data = {
type: 'A',
name: 'example.com',
content: '192.0.2.1',
ttl: 300
};
const response = await fetch(`https://api.cloudflare.com/client/v4/zones/${zoneId}/dns_records`, {
method: 'POST',
headers,
body: JSON.stringify(data)
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const json = await response.json();
console.log(json);
import axios from 'axios';
import { env } from 'node:process';
const zoneId = env.ZONE_ID;
const apiToken = env.CF_API_TOKEN;
const headers = {
'Authorization': `Bearer ${apiToken}`,
'Content-Type': 'application/json'
};
const data = {
type: 'A',
name: 'example.com',
content: '192.0.2.1',
ttl: 300
};
try {
const response = await axios.post(
`https://api.cloudflare.com/client/v4/zones/${zoneId}/dns_records`,
data,
{ headers }
);
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"
"io"
"log"
"net/http"
"os"
)
type DNSRecord struct {
Type string `json:"type"`
Name string `json:"name"`
Content string `json:"content"`
TTL int `json:"ttl"`
}
func main() {
zoneID := os.Getenv("ZONE_ID")
apiToken := os.Getenv("CF_API_TOKEN")
data := DNSRecord{
Type: "A",
Name: "example.com",
Content: "192.0.2.1",
TTL: 300,
}
body, err := json.Marshal(data)
if err != nil {
log.Fatal(err)
}
req, err := http.NewRequest(
"POST",
fmt.Sprintf("https://api.cloudflare.com/client/v4/zones/%s/dns_records", zoneID),
bytes.NewBuffer(body),
)
if err != nil {
log.Fatal(err)
}
req.Header.Set("Authorization", "Bearer "+apiToken)
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 {
body, _ := io.ReadAll(resp.Body)
log.Fatalf("HTTP error! status: %s, body: %s", resp.Status, body)
}
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');
$apiToken = getenv('CF_API_TOKEN');
$data = [
'type' => 'A',
'name' => 'example.com',
'content' => '192.0.2.1',
'ttl' => 300
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.cloudflare.com/client/v4/zones/{$zoneId}/dns_records");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $apiToken,
'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
if (curl_errno($ch)) {
die('Error: ' . curl_error($ch));
}
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode !== 200) {
die("HTTP error! status: {$httpCode}, body: {$response}");
}
$json = json_decode($response, true);
print_r($json);
require 'net/http'
require 'json'
require 'uri'
zone_id = ENV['ZONE_ID']
api_token = ENV['CF_API_TOKEN']
uri = URI.parse("https://api.cloudflare.com/client/v4/zones/#{zone_id}/dns_records")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Post.new(uri.request_uri)
request['Authorization'] = "Bearer #{api_token}"
request['Content-Type'] = 'application/json'
request.body = {
type: 'A',
name: 'example.com',
content: '192.0.2.1',
ttl: 300
}.to_json
response = http.request(request)
unless response.is_a?(Net::HTTPSuccess)
raise "HTTP error! status: #{response.code}, body: #{response.body}"
end
puts JSON.parse(response.body)
import Foundation
let zoneId = ProcessInfo.processInfo.environment["ZONE_ID"] ?? ""
let apiToken = ProcessInfo.processInfo.environment["CF_API_TOKEN"] ?? ""
let url = URL(string: "https://api.cloudflare.com/client/v4/zones/" + zoneId + "/dns_records")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Bearer " + apiToken, forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let body: [String: Any] = [
"type": "A",
"name": "example.com",
"content": "192.0.2.1",
"ttl": 300
]
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 else {
print("Invalid response")
return
}
guard (200...299).contains(httpResponse.statusCode) else {
print("HTTP error! status: \(httpResponse.statusCode)")
if let data = data, let body = String(data: data, encoding: .utf8) {
print("Body: \(body)")
}
return
}
if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data) as? [String: Any]
print(json ?? "")
} catch {
print("JSON parsing error: \(error)")
}
}
}
task.resume()
RunLoop.main.run()
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 api_token = env::var("CF_API_TOKEN")?;
let client = Client::new();
let url = format!(
"https://api.cloudflare.com/client/v4/zones/{}/dns_records",
zone_id
);
let body = json!({
"type": "A",
"name": "example.com",
"content": "192.0.2.1",
"ttl": 300
});
let response = client
.post(&url)
.header("Authorization", format!("Bearer {}", api_token))
.header("Content-Type", "application/json")
.json(&body)
.send()?;
if !response.status().is_success() {
eprintln!(
"HTTP error! status: {}",
response.status()
);
let body = response.text()?;
eprintln!("Body: {}", body);
return Err("Request failed".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()
{
var zoneId = Environment.GetEnvironmentVariable("ZONE_ID");
var apiToken = Environment.GetEnvironmentVariable("CF_API_TOKEN");
var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post,
$"https://api.cloudflare.com/client/v4/zones/{zoneId}/dns_records");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", apiToken);
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var body = new
{
type = "A",
name = "example.com",
content = "192.0.2.1",
ttl = 300
};
request.Content = new StringContent(JsonSerializer.Serialize(body));
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = await client.SendAsync(request);
if (!response.IsSuccessStatusCode)
{
var errorBody = await response.Content.ReadAsStringAsync();
Console.WriteLine($"HTTP error! status: {response.StatusCode}, body: {errorBody}");
return;
}
var json = await response.Content.ReadAsStringAsync();
Console.WriteLine(json);
}
}