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 xoxp-1234567890-1234567890-1234567890-12345" \
  -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_TOKEN']}"},
    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_TOKEN']}"},
    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_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_TOKEN}`,
      'Content-Type': 'application/json'
    }
  }
);

console.log(response.data);

Go · net/http

package main

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

func main() {
	client := &http.Client{}
	url := "https://slack.com/api/conversations.archive"

	body := map[string]string{"channel": "C1234567890"}
	jsonBody, _ := json.Marshal(body)

	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonBody))
	if err != nil {
		log.Fatal(err)
	}

	req.Header.Set("Authorization", "Bearer "+os.Getenv("SLACK_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)
	}

	bodyBytes, _ := ioutil.ReadAll(resp.Body)
	var result map[string]interface{}
	json.Unmarshal(bodyBytes, &result)
	fmt.Println(result)
}

PHP · cURL

<?php
$ch = curl_init();

$url = 'https://slack.com/api/conversations.archive';
$data = ['channel' => 'C1234567890'];

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Authorization: Bearer ' . getenv('SLACK_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_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_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 url = "https://slack.com/api/conversations.archive";
    let token = env::var("SLACK_TOKEN")?;

    let response = client
        .post(url)
        .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.Threading.Tasks;
using System.Text.Json;

class Program
{
    static async Task Main()
    {
        var client = new HttpClient();
        var url = "https://slack.com/api/conversations.archive";
        var token = Environment.GetEnvironmentVariable("SLACK_TOKEN");

        var body = new { channel = "C1234567890" };
        var content = new StringContent(JsonSerializer.Serialize(body));
        content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

        var response = await client.PostAsync(url, content);
        if (!response.IsSuccessStatusCode)
        {
            throw new Exception($"HTTP error! status: {response.StatusCode}");
        }

        var responseBody = await response.Content.ReadAsStringAsync();
        var result = JsonSerializer.Deserialize<object>(responseBody);
        Console.WriteLine(result);
    }
}

Translation notes

  • All implementations use environment variables for the Slack token (SLACK_TOKEN)
  • JSON bodies are constructed as objects/dicts, not raw strings
  • Error handling checks HTTP status and raises/logs errors
  • Content-Type header is explicitly set to 'application/json' where required
  • Go and Rust examples use blocking clients for simplicity; async variants are available
  • Swift uses URLSession with a synchronous run loop for simplicity in examples

Common pitfalls when porting

  • Forgetting to set Content-Type header may cause Slack API to reject the request
  • Not reading the response body can lead to silent failures
  • Using raw strings for JSON bodies instead of proper serialization
  • Ignoring HTTP status codes can mask API errors
  • Hardcoding tokens in source code instead of using environment variables

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 for the token?

Environment variables are the standard way to handle secrets in applications, avoiding hardcoding sensitive data in source code or version control.

Can I use async/await in Go or Rust?

Yes, both languages support async/await. In Go, use 'net/http' with 'context' for cancellation. In Rust, use 'reqwest' with async runtime like 'tokio'.

How do I handle pagination in Slack API responses?

Slack API responses often include a 'response_metadata' object with a 'next_cursor' field. Use this to make subsequent requests until 'next_cursor' is empty.

Why does the Swift example use a synchronous run loop?

The example uses a synchronous run loop for simplicity in a console app. In real iOS/macOS apps, use URLSession with async/await or completion handlers.