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 \
  -H "Authorization: Bearer xoxb-1234567890" \
  -H "Content-Type: application/json" \
  -d '{"channel":"C12345678"}'

Python · requests

import os
import requests

SLACK_TOKEN = os.environ.get("SLACK_TOKEN")

response = requests.post(
    "https://slack.com/api/conversations.join",
    headers={
        "Authorization": f"Bearer {SLACK_TOKEN}",
        "Content-Type": "application/json"
    },
    json={"channel": "C12345678"}
)

if response.status_code != 200:
    raise Exception(f"Request failed with status {response.status_code}")

print(response.json())

Python · httpx

import os
import httpx

SLACK_TOKEN = os.environ.get("SLACK_TOKEN")

async def join_conversation():
    async with httpx.AsyncClient() as client:
        response = await client.post(
            "https://slack.com/api/conversations.join",
            headers={
                "Authorization": f"Bearer {SLACK_TOKEN}",
                "Content-Type": "application/json"
            },
            json={"channel": "C12345678"}
        )
        if response.status_code != 200:
            raise Exception(f"Request failed with status {response.status_code}")
        return response.json()

# For synchronous usage:
# with httpx.Client() as client:
#     response = client.post(...)
#     if response.status_code != 200:
#         raise Exception(...)
#     print(response.json())

Node.js · fetch

import fetch from 'node-fetch';

const SLACK_TOKEN = process.env.SLACK_TOKEN;

(async () => {
  const response = await fetch('https://slack.com/api/conversations.join', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${SLACK_TOKEN}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ channel: 'C12345678' })
  });

  if (!response.ok) {
    throw new Error(`Request failed with status ${response.status}`);
  }

  const data = await response.json();
  console.log(data);
})();

Node.js · axios

const axios = require('axios');

const SLACK_TOKEN = process.env.SLACK_TOKEN;

(async () => {
  try {
    const response = await axios.post(
      'https://slack.com/api/conversations.join',
      { channel: 'C12345678' },
      {
        headers: {
          'Authorization': `Bearer ${SLACK_TOKEN}`,
          'Content-Type': 'application/json'
        }
      }
    );

    if (response.status !== 200) {
      throw new Error(`Request failed with status ${response.status}`);
    }

    console.log(response.data);
  } catch (error) {
    console.error('Error:', error.message);
  }
})();

Go · net/http

package main

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

type RequestBody struct {
	Channel string `json:"channel"`
}

func main() {
	slackToken := os.Getenv("SLACK_TOKEN")
	if slackToken == "" {
		log.Fatal("SLACK_TOKEN environment variable not set")
	}

	body := RequestBody{Channel: "C12345678"}
	jsonBody, err := json.Marshal(body)
	if err != nil {
		log.Fatal(err)
	}

	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 "+slackToken)
	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("Request failed with status %d", resp.StatusCode)
	}

	var result map[string]interface{}
	if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
		log.Fatal(err)
	}
	fmt.Println(result)
}

PHP · cURL

<?php

$slackToken = getenv('SLACK_TOKEN');
if (empty($slackToken)) {
    die('SLACK_TOKEN environment variable not set');
}

$ch = curl_init('https://slack.com/api/conversations.join');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['channel' => 'C12345678']));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Authorization: Bearer ' . $slackToken,
    'Content-Type: application/json'
]);

$response = curl_exec($ch);
if (curl_errno($ch)) {
    die('Request failed: ' . curl_error($ch));
}

$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode !== 200) {
    die("Request failed with status $httpCode");
}

$decoded = json_decode($response, true);
if (json_last_error() !== JSON_ERROR_NONE) {
    die('Failed to decode response');
}

print_r($decoded);
curl_close($ch);

Ruby · net/http

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

slack_token = ENV.fetch('SLACK_TOKEN')
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 #{slack_token}"
request['Content-Type'] = 'application/json'
request.body = { channel: 'C12345678' }.to_json

response = http.request(request)

unless response.code == '200'
  raise "Request failed with status #{response.code}"
end

puts JSON.parse(response.body)

Swift · URLSession

import Foundation

guard let slackToken = ProcessInfo.processInfo.environment["SLACK_TOKEN"] else {
    fatalError("SLACK_TOKEN environment variable not set")
}

let url = URL(string: "https://slack.com/api/conversations.join")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Bearer \(slackToken)", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

let body: [String: Any] = ["channel": "C12345678"]
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 else {
        fatalError("Invalid response")
    }

    guard httpResponse.statusCode == 200 else {
        fatalError("Request failed with status \(httpResponse.statusCode)")
    }

    guard let data = data else {
        fatalError("No data received")
    }

    do {
        let json = try JSONSerialization.jsonObject(with: data) as? [String: Any]
        print(json ?? "")
    } catch {
        fatalError("Failed to decode response: \(error)")
    }
}

task.resume()

// Keep the program running to allow the async task to complete
RunLoop.main.run()

Rust · reqwest

use std::collections::HashMap;
use std::env;
use reqwest;
use serde_json::json;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let slack_token = env::var("SLACK_TOKEN")?;

    let client = reqwest::Client::new();
    let mut headers = reqwest::header::HeaderMap::new();
    headers.insert(
        "Authorization",
        format!("Bearer {}", slack_token).parse()?,
    );
    headers.insert(
        "Content-Type",
        "application/json".parse()?,
    );

    let body = json!({"channel": "C12345678"});

    let response = client
        .post("https://slack.com/api/conversations.join")
        .headers(headers)
        .json(&body)
        .send()
        .await?;

    if !response.status().is_success() {
        return Err(format!("Request failed with status {}", response.status()).into());
    }

    let json: HashMap<String, serde_json::Value> = response.json().await?;
    println!("{:?}", json);

    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 slackToken = Environment.GetEnvironmentVariable("SLACK_TOKEN");
        if (string.IsNullOrEmpty(slackToken))
        {
            Console.WriteLine("SLACK_TOKEN environment variable not set");
            return;
        }

        using var client = new HttpClient();
        client.BaseAddress = new Uri("https://slack.com/");

        var request = new HttpRequestMessage(HttpMethod.Post, "api/conversations.join");
        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", slackToken);
        request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

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

        var response = await client.SendAsync(request);
        if (!response.IsSuccessStatusCode)
        {
            Console.WriteLine($"Request failed with status {response.StatusCode}");
            return;
        }

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

Translation notes

  • All implementations use idiomatic HTTP clients for each language
  • Bearer token is read from environment variable SLACK_TOKEN
  • JSON body is sent as a structured object, not a raw string
  • Error handling checks HTTP status and ensures response body is read
  • Async/await is used where idiomatic (Node.js, Go, Swift, Rust, C#)
  • Synchronous alternatives are provided where applicable (Python requests, Go sync, PHP)
  • Headers are set explicitly for clarity and maintainability

Common pitfalls when porting

  • Forgetting to set SLACK_TOKEN environment variable will cause runtime errors
  • Not checking HTTP status codes can lead to silent failures
  • Manually stringifying JSON bodies instead of using library methods can introduce errors
  • In Go, forgetting to close the response body can lead to resource leaks
  • In Swift, the async task must be allowed to complete (RunLoop.main.run())
  • In Rust, the reqwest client requires the tokio runtime for async operations

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 instead of hardcoding?

Environment variables separate configuration from code, reducing the risk of accidental exposure in version control or logs. They also allow different deployments to use different credentials without code changes.

How do I handle pagination or rate limits in the Slack API?

Slack API responses include rate limit headers (X-RateLimit-Limit, X-RateLimit-Remaining). Implement retry logic with exponential backoff when these headers indicate limits are approaching. Use the 'cursor' parameter for pagination in endpoints that support it.

Can I use a different HTTP client library?

Yes, but ensure it supports the same features: automatic JSON serialization, header management, and proper error handling. Popular alternatives include urllib3 (Python), got (Go), and RestSharp (C#).

Why is the Swift example using RunLoop.main.run()?

Swift's URLSession is asynchronous. The RunLoop.main.run() keeps the program running long enough for the async task to complete. In a real app, you'd typically use this in a proper async context (e.g., Swift Concurrency with async/await).