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.join --header "Authorization: Bearer xoxb-1234567890-abcdefgh" --data '{"channel":"C1234567890"}'

Python · requests

import os
import requests

response = requests.post(
    "https://slack.com/api/conversations.join",
    headers={"Authorization": f"Bearer {os.environ['SLACK_BOT_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.join",
    headers={"Authorization": f"Bearer {os.environ['SLACK_BOT_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.join', {
  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.join',
  { 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.join",
		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: %d", resp.StatusCode)
	}
	
	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.join');
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");
}

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

curl_close($ch);

Ruby · net/http

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

uri = URI.parse('https://slack.com/api/conversations.join')
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.join")!
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.join")
        .header("Authorization", format!("Bearer {}", token))
        .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.join");
        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
        request.Content = new StringContent(JsonSerializer.Serialize(new { channel = "C1234567890" }), System.Text.Encoding.UTF8, "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<System.Text.Json.JsonElement>(content);
        Console.WriteLine(result);
    }
}

Translation notes

  • All implementations use the idiomatic HTTP client for the language.
  • Bearer token is read from environment variable SLACK_BOT_TOKEN to avoid hardcoding.
  • JSON body is sent as a structured object, not a raw string.
  • Error handling checks HTTP status and throws/raises on failure.
  • Content-Type header is set to 'application/json' explicitly where required.

Common pitfalls when porting

  • Forgetting to set Content-Type header may cause the server to reject the request.
  • Not reading the token from environment variables risks exposing secrets in version control.
  • In Go, forgetting to close the response body can lead to resource leaks.
  • In Swift, the URLSession task must be started with task.resume().
  • In Rust, using reqwest::blocking requires a runtime like tokio for async contexts.

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 secrets?

Environment variables separate configuration from code, reducing the risk of accidental secret exposure in version control or logs.

Can I use async/await in all languages?

Most modern languages support async/await, but some (like Go with blocking client) may require explicit runtime setup for async contexts.

How do I handle rate limits?

Check the response headers for rate limit information and implement exponential backoff in your retry logic.