Qaynaq LABS · TOOLS

CURL → CODE · POST · BEARER

cURL → 10 languages

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

Source cURL
curl -X POST https://slack.com/api/conversations.join \
  -H "Authorization: Bearer xoxb-1234567890-1234567890123-abcdefghijklmnopqrstuvwx" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "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']}",
        "Content-Type": "application/x-www-form-urlencoded"
    },
    data={"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']}",
        "Content-Type": "application/x-www-form-urlencoded"
    },
    data={"channel": "C1234567890"}
)
response.raise_for_status()
print(response.json())

Node.js · fetch

import fetch from 'node-fetch';
import 'dotenv/config';

const response = await fetch('https://slack.com/api/conversations.join', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${process.env.SLACK_BOT_TOKEN}`,
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  body: new URLSearchParams({ 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';
import 'dotenv/config';

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

Go · net/http

package main

import (
	"fmt"
	"net/http"
	"net/url"
	"os"
)

func main() {
	token := os.Getenv("SLACK_BOT_TOKEN")
	if token == "" {
		panic("SLACK_BOT_TOKEN environment variable not set")
	}

	form := url.Values{}
	form.Add("channel", "C1234567890")

	req, err := http.NewRequest(
		"POST",
		"https://slack.com/api/conversations.join",
		strings.NewReader(form.Encode()),
	)
	if err != nil {
		panic(err)
	}

	req.Header.Set("Authorization", "Bearer "+token)
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		panic(fmt.Sprintf("HTTP error! status: %s", resp.Status))
	}

	// Handle response body as needed
}

PHP · cURL

<?php

$token = getenv('SLACK_BOT_TOKEN');
if (empty($token)) {
    throw new RuntimeException('SLACK_BOT_TOKEN environment variable not set');
}

$ch = curl_init('https://slack.com/api/conversations.join');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(['channel' => 'C1234567890']));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Authorization: Bearer ' . $token,
    'Content-Type: application/x-www-form-urlencoded'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);
if (curl_errno($ch)) {
    throw new RuntimeException('cURL error: ' . curl_error($ch));
}
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode !== 200) {
    throw new RuntimeException("HTTP error! status: $httpCode");
}
curl_close($ch);

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

Ruby · net/http

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

token = ENV.fetch('SLACK_BOT_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 #{token}"
request['Content-Type'] = 'application/x-www-form-urlencoded'
request.set_form_data({ channel: 'C1234567890' })

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

guard let token = ProcessInfo.processInfo.environment["SLACK_BOT_TOKEN"] else {
    fatalError("SLACK_BOT_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 \(token)", forHTTPHeaderField: "Authorization")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")

let body = "channel=C1234567890"
request.httpBody = body.data(using: .utf8)

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::collections::HashMap;
use std::env;
use reqwest::blocking::Client;
use reqwest::header;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let token = env::var("SLACK_BOT_TOKEN")?;
    let client = Client::new();
    
    let mut params = HashMap::new();
    params.insert("channel", "C1234567890");
    
    let response = client
        .post("https://slack.com/api/conversations.join")
        .header(header::AUTHORIZATION, format!("Bearer {}", token))
        .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
        .form(&params)
        .send()?;
    
    if !response.status().is_success() {
        return Err(format!("HTTP error! status: {}", response.status()).into());
    }
    
    let json: serde_json::Value = response.json()?;
    println!("{:?}", json);
    Ok(())
}

C# · HttpClient

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        var token = Environment.GetEnvironmentVariable("SLACK_BOT_TOKEN");
        if (string.IsNullOrEmpty(token))
        {
            throw new Exception("SLACK_BOT_TOKEN environment variable not set");
        }

        using var client = new HttpClient();
        var form = new Dictionary<string, string>
        {
            { "channel", "C1234567890" }
        };

        var response = await client.PostAsync(
            "https://slack.com/api/conversations.join",
            new FormUrlEncodedContent(form)
        );

        response.EnsureSuccessStatusCode();
        var json = await response.Content.ReadAsStringAsync();
        Console.WriteLine(json);
    }
}

Translation notes

  • All implementations use environment variables for secrets (SLACK_BOT_TOKEN).
  • Python, Node.js, Go, Ruby, Swift, Rust, and C# use idiomatic HTTP clients.
  • PHP uses cURL for direct compatibility with the original command.
  • Form data is sent as URL-encoded in all cases.
  • Error handling checks HTTP status and raises exceptions where appropriate.

Common pitfalls when porting

  • Forgetting to set the SLACK_BOT_TOKEN environment variable will cause failures.
  • In Go, ensure the 'strings' package is imported for form encoding.
  • In Swift, URLSession is asynchronous; the example uses RunLoop for simplicity but real apps should use async/await.
  • In Rust, the 'reqwest' crate must be added to Cargo.toml with the 'blocking' feature.
  • In PHP, ensure the 'curl' extension is enabled in php.ini.

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 configuration to vary between environments.

Can I use JSON instead of form data for the request body?

Yes, but the original cURL uses form data. Change the Content-Type to 'application/json' and send a JSON body if needed.

How do I handle pagination or large responses?

Most libraries provide streaming or pagination helpers. For example, in Python's requests, use response.iter_content().

Why does the Swift example use RunLoop.main.run()?

The example is simplified for demonstration. In a real app, use async/await with URLSession.data(for:delegate:) or Combine.