Qaynaq LABS · TOOLS

CURL → CODE · POST · BEARER

cURL → 10 languages

POST slack.com · body: json · secrets replaced with env vars.

Source cURL
curl -X POST https://slack.com/api/conversations.archive \
  -H "Authorization: Bearer xoxb-1234567890-1234567890123-abcdefghijklmnopqrstuvwx" \
  -H "Content-Type: application/json" \
  -d '{"channel":"C1234567890"}'

Python · requests

import os
import requests

response = requests.post(
    "https://slack.com/api/conversations.archive",
    headers={
        "Authorization": f"Bearer {os.environ['SLACK_BOT_TOKEN']}",
        "Content-Type": "application/json"
    },
    json={"channel": "C1234567890"}
)
response.raise_for_status()
print(response.json())

Python · httpx

import os
import httpx

response = httpx.post(
    "https://slack.com/api/conversations.archive",
    headers={
        "Authorization": f"Bearer {os.environ['SLACK_BOT_TOKEN']}",
        "Content-Type": "application/json"
    },
    json={"channel": "C1234567890"}
)
response.raise_for_status()
print(response.json())

Node.js · fetch

import fetch from 'node-fetch';

const response = await fetch('https://slack.com/api/conversations.archive', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${process.env.SLACK_BOT_TOKEN}`,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ channel: 'C1234567890' })
});
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
const data = await response.json();
console.log(data);

Node.js · axios

import axios from 'axios';

const response = await axios.post(
  'https://slack.com/api/conversations.archive',
  { channel: 'C1234567890' },
  {
    headers: {
      'Authorization': `Bearer ${process.env.SLACK_BOT_TOKEN}`,
      'Content-Type': 'application/json'
    }
  }
);
console.log(response.data);

Go · net/http

package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"os"
)

func main() {
	client := &http.Client{}
	
	body := map[string]string{"channel": "C1234567890"}
	jsonBody, _ := json.Marshal(body)
	
	req, err := http.NewRequest(
		"POST",
		"https://slack.com/api/conversations.archive",
		bytes.NewBuffer(jsonBody),
	)
	if err != nil {
		log.Fatal(err)
	}
	
	req.Header.Set("Authorization", "Bearer "+os.Getenv("SLACK_BOT_TOKEN"))
	req.Header.Set("Content-Type", "application/json")
	
	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 · cURL

<?php

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'https://slack.com/api/conversations.archive');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['channel' => 'C1234567890']));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Authorization: Bearer ' . getenv('SLACK_BOT_TOKEN'),
    '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);
if ($httpCode !== 200) {
    die("HTTP error! status: $httpCode");
}

$decoded = json_decode($response, true);
print_r($decoded);

curl_close($ch);
?>

Ruby · net/http

require 'net/http'
require 'json'
require 'uri'

uri = URI.parse('https://slack.com/api/conversations.archive')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true

request = Net::HTTP::Post.new(uri.request_uri)
request['Authorization'] = "Bearer #{ENV['SLACK_BOT_TOKEN']}"
request['Content-Type'] = 'application/json'
request.body = { channel: 'C1234567890' }.to_json

response = http.request(request)
unless response.is_a?(Net::HTTPSuccess)
  raise "HTTP error! status: #{response.code}"
end

puts JSON.parse(response.body)

Swift · URLSession

import Foundation

let url = URL(string: "https://slack.com/api/conversations.archive")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Bearer \(ProcessInfo.processInfo.environment["SLACK_BOT_TOKEN"] ?? "")", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

let body: [String: String] = ["channel": "C1234567890"]
request.httpBody = try? JSONSerialization.data(withJSONObject: body)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    if let error = error {
        fatalError("Error: \(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()

Rust · reqwest

use std::env;
use reqwest::blocking::Client;
use serde_json::json;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::new();
    let token = env::var("SLACK_BOT_TOKEN")?;
    
    let response = client
        .post("https://slack.com/api/conversations.archive")
        .header("Authorization", format!("Bearer {}", token))
        .header("Content-Type", "application/json")
        .json(&json!({"channel": "C1234567890"}))
        .send()?;
    
    if !response.status().is_success() {
        return Err(format!("HTTP error! status: {}", response.status()).into());
    }
    
    let body = response.json::<serde_json::Value>()?;
    println!("{:?}", body);
    Ok(())
}

C# · HttpClient

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 client = new HttpClient();
        var token = Environment.GetEnvironmentVariable("SLACK_BOT_TOKEN");
        
        var request = new HttpRequestMessage(HttpMethod.Post, "https://slack.com/api/conversations.archive");
        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
        request.Content = new StringContent(JsonSerializer.Serialize(new { channel = "C1234567890" }));
        request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
        
        var response = await client.SendAsync(request);
        if (!response.IsSuccessStatusCode)
        {
            throw new Exception($"HTTP error! status: {response.StatusCode}");
        }
        
        var content = await response.Content.ReadAsStringAsync();
        var result = JsonSerializer.Deserialize<object>(content);
        Console.WriteLine(result);
    }
}

Translation notes

  • All implementations use environment variables for secrets (SLACK_BOT_TOKEN)
  • JSON bodies are sent as structured objects, not raw strings
  • Error handling checks HTTP status and raises/logs errors
  • Headers are preserved exactly as in the cURL command
  • Each language uses its idiomatic HTTP client library

Common pitfalls when porting

  • Forgetting to set the Content-Type header in languages that don't auto-set it
  • Not properly escaping environment variable values in headers
  • Ignoring SSL/TLS verification in Go or other low-level clients
  • Assuming JSON serialization will always work without error handling
  • Using string concatenation for headers instead of proper header builders

About cURL → code translation

cURL is the lingua franca of API documentation: every vendor docs page ships a cURL snippet you can paste into a terminal and immediately see the API working. Translating that into your actual application code shouldn't be a 20-minute Stack-Overflow safari, but without a good translator it usually is.

Qaynaq Labs' cURL → code tool reads the full command — method, URL, headers, query params, body type, and auth — and emits idiomatic client code in 10 languages. Authentication goes through environment variables by default, request bodies become language-native data structures (not raw JSON strings), and minimal error handling is included.

Frequently asked

Why use environment variables instead of hardcoding tokens?

Environment variables prevent secrets from being committed to version control and allow different configurations across environments without code changes.

How do I handle rate limits in these implementations?

Implement retry logic with exponential backoff using the Retry-After header or a library like python-tenacity.

Can I use a different JSON library in these examples?

Yes, but ensure it properly serializes objects to JSON strings and handles nested structures correctly.