import os
import requests
response = requests.post(
f"https://api.cloudflare.com/client/v4/accounts/{os.environ['ACCOUNT_ID']}/workers/scripts/{os.environ['SCRIPT_NAME']}/environments/production/secrets",
headers={
"Authorization": f"Bearer {os.environ['CF_API_TOKEN']}",
"Content-Type": "application/json"
},
json={"name": "SECRET_KEY", "text": "value123", "type": "secret_text"}
)
response.raise_for_status()
print(response.json())
import os
import httpx
async def main():
async with httpx.AsyncClient() as client:
response = await client.post(
f"https://api.cloudflare.com/client/v4/accounts/{os.environ['ACCOUNT_ID']}/workers/scripts/{os.environ['SCRIPT_NAME']}/environments/production/secrets",
headers={
"Authorization": f"Bearer {os.environ['CF_API_TOKEN']}",
"Content-Type": "application/json"
},
json={"name": "SECRET_KEY", "text": "value123", "type": "secret_text"}
)
response.raise_for_status()
print(response.json())
if __name__ == "__main__":
import asyncio
asyncio.run(main())
import fetch from 'node-fetch';
import { env } from 'process';
(async () => {
const response = await fetch(
`https://api.cloudflare.com/client/v4/accounts/${env.ACCOUNT_ID}/workers/scripts/${env.SCRIPT_NAME}/environments/production/secrets`,
{
method: 'POST',
headers: {
'Authorization': `Bearer ${env.CF_API_TOKEN}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({"name": "SECRET_KEY", "text": "value123", "type": "secret_text"})
}
);
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
console.log(await response.json());
})();
import axios from 'axios';
import { env } from 'process';
(async () => {
const response = await axios.post(
`https://api.cloudflare.com/client/v4/accounts/${env.ACCOUNT_ID}/workers/scripts/${env.SCRIPT_NAME}/environments/production/secrets`,
{"name": "SECRET_KEY", "text": "value123", "type": "secret_text"},
{
headers: {
'Authorization': `Bearer ${env.CF_API_TOKEN}`,
'Content-Type': 'application/json'
}
}
);
console.log(response.data);
})();
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"os"
)
type Secret struct {
Name string `json:"name"`
Text string `json:"text"`
Type string `json:"type"`
}
func main() {
accountID := os.Getenv("ACCOUNT_ID")
scriptName := os.Getenv("SCRIPT_NAME")
apiToken := os.Getenv("CF_API_TOKEN")
url := fmt.Sprintf("https://api.cloudflare.com/client/v4/accounts/%s/workers/scripts/%s/environments/production/secrets", accountID, scriptName)
payload := Secret{Name: "SECRET_KEY", Text: "value123", Type: "secret_text"}
payloadBytes, _ := json.Marshal(payload)
req, err := http.NewRequest("POST", url, bytes.NewBuffer(payloadBytes))
if err != nil {
log.Fatal(err)
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", 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 {
log.Fatalf("HTTP error! status: %s", resp.Status)
}
var result map[string]interface{}
json.NewDecoder(resp.Body).Decode(&result)
fmt.Println(result)
}
<?php
$accountId = getenv('ACCOUNT_ID');
$scriptName = getenv('SCRIPT_NAME');
$apiToken = getenv('CF_API_TOKEN');
$url = "https://api.cloudflare.com/client/v4/accounts/{$accountId}/workers/scripts/{$scriptName}/environments/production/secrets";
$data = [
'name' => 'SECRET_KEY',
'text' => 'value123',
'type' => 'secret_text'
];
$options = [
'http' => [
'header' => [
"Authorization: Bearer {$apiToken}",
"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("HTTP request failed");
}
$response = json_decode($result, true);
print_r($response);
require 'net/http'
require 'json'
require 'uri'
account_id = ENV['ACCOUNT_ID']
script_name = ENV['SCRIPT_NAME']
api_token = ENV['CF_API_TOKEN']
uri = URI.parse("https://api.cloudflare.com/client/v4/accounts/#{account_id}/workers/scripts/#{script_name}/environments/production/secrets")
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 = { name: 'SECRET_KEY', text: 'value123', type: 'secret_text' }.to_json
response = http.request(request)
unless response.is_a?(Net::HTTPSuccess)
raise "HTTP error! status: #{response.code}"
end
puts JSON.parse(response.body)
import Foundation
let accountId = ProcessInfo.processInfo.environment["ACCOUNT_ID"] ?? ""
let scriptName = ProcessInfo.processInfo.environment["SCRIPT_NAME"] ?? ""
let apiToken = ProcessInfo.processInfo.environment["CF_API_TOKEN"] ?? ""
let url = URL(string: "https://api.cloudflare.com/client/v4/accounts/" + accountId + "/workers/scripts/" + scriptName + "/environments/production/secrets")!
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] = [
"name": "SECRET_KEY",
"text": "value123",
"type": "secret_text"
]
request.httpBody = try? JSONSerialization.data(withJSONObject: body)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error {
fatalError("Request failed: \(error)")
}
guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
fatalError("HTTP error! status: \((response as? HTTPURLResponse)?.statusCode ?? 0)")
}
if let data = data, let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
print(json)
}
}
task.resume()
RunLoop.main.run()
use reqwest;
use serde_json::json;
use std::env;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let account_id = env::var("ACCOUNT_ID")?;
let script_name = env::var("SCRIPT_NAME")?;
let api_token = env::var("CF_API_TOKEN")?;
let url = format!(
"https://api.cloudflare.com/client/v4/accounts/{}/workers/scripts/{}/environments/production/secrets",
account_id, script_name
);
let client = reqwest::Client::new();
let response = client
.post(&url)
.header("Authorization", format!("Bearer {}", api_token))
.header("Content-Type", "application/json")
.json(&json!({"name": "SECRET_KEY", "text": "value123", "type": "secret_text"}))
.send()
.await?;
if !response.status().is_success() {
return Err(format!("HTTP error! status: {}", response.status()).into());
}
let body = response.json::<serde_json::Value>().await?;
println!("{}", body);
Ok(())
}
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Text.Json;
class Program
{
static async Task Main()
{
var accountId = Environment.GetEnvironmentVariable("ACCOUNT_ID");
var scriptName = Environment.GetEnvironmentVariable("SCRIPT_NAME");
var apiToken = Environment.GetEnvironmentVariable("CF_API_TOKEN");
var url = $"https://api.cloudflare.com/client/v4/accounts/{accountId}/workers/scripts/{scriptName}/environments/production/secrets";
var data = new { name = "SECRET_KEY", text = "value123", type = "secret_text" };
using var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiToken);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.PostAsJsonAsync(url, data);
if (!response.IsSuccessStatusCode)
{
throw new Exception($"HTTP error! status: {response.StatusCode}");
}
var result = await response.Content.ReadAsStringAsync();
Console.WriteLine(result);
}
}