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/chat.postMessage -H "Authorization: Bearer xoxb-1234567890-123456789012-abcdefghijklmnopqrstuvwx" -d "channel=C12345678&text=Hello from cURL"

Python · requests

import os
import requests

response = requests.post(
    "https://slack.com/api/chat.postMessage",
    headers={"Authorization": f"Bearer {os.environ['SLACK_BOT_TOKEN']}"},
    data={"channel": "C12345678", "text": "Hello from cURL"}
)
response.raise_for_status()
print(response.json())

Python · httpx

import os
import httpx

response = httpx.post(
    "https://slack.com/api/chat.postMessage",
    headers={"Authorization": f"Bearer {os.environ['SLACK_BOT_TOKEN']}"},
    data={"channel": "C12345678", "text": "Hello from cURL"}
)
response.raise_for_status()
print(response.json())

Node.js · fetch

import fetch from 'node-fetch';
import { env } from 'process';

(async () => {
  const response = await fetch('https://slack.com/api/chat.postMessage', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${env.SLACK_BOT_TOKEN}`
    },
    body: new URLSearchParams({
      channel: 'C12345678',
      text: 'Hello from cURL'
    })
  });
  if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
  console.log(await response.json());
})();

Node.js · axios

import axios from 'axios';
import { env } from 'process';

(async () => {
  const response = await axios.post(
    'https://slack.com/api/chat.postMessage',
    new URLSearchParams({
      channel: 'C12345678',
      text: 'Hello from cURL'
    }),
    {
      headers: {
        'Authorization': `Bearer ${env.SLACK_BOT_TOKEN}`
      }
    }
  );
  console.log(response.data);
})();

Go · net/http

package main

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

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

	form := url.Values{}
	form.Add("channel", "C12345678")
	form.Add("text", "Hello from cURL")

	req, err := http.NewRequest(
		"POST",
		"https://slack.com/api/chat.postMessage",
		strings.NewReader(form.Encode()),
	)
	if err != nil {
		log.Fatal(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 {
		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{}
	if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
		log.Fatal(err)
	}
	fmt.Println(result)
}

PHP · cURL

<?php

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

$ch = curl_init('https://slack.com/api/chat.postMessage');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
    'channel' => 'C12345678',
    'text' => 'Hello from cURL'
]));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Authorization: Bearer ' . $token
]);

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

$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode !== 200) {
    die("HTTP error! status: $httpCode");
}

$json = json_decode($response, true);
if (json_last_error() !== JSON_ERROR_NONE) {
    die('JSON decode error: ' . json_last_error_msg());
}

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/chat.postMessage')

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.set_form_data({
  'channel' => 'C12345678',
  'text' => 'Hello from cURL'
})

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/chat.postMessage")!
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=C12345678&text=Hello from cURL"
request.httpBody = body.data(using: .utf8)

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 (200...299).contains(httpResponse.statusCode) else {
        fatalError("HTTP error! status: \(httpResponse.statusCode)")
    }
    guard let data = data else {
        fatalError("No data received")
    }
    do {
        if let json = try JSONSerialization.jsonObject(with: data) as? [String: Any] {
            print(json)
        }
    } catch {
        fatalError("JSON decode error: \(error)")
    }
}
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 headers = header::HeaderMap::new();
    headers.insert(
        "Authorization",
        header::HeaderValue::from_str(&format!("Bearer {}", token))?,
    );
    headers.insert(
        "Content-Type",
        header::HeaderValue::from_static("application/x-www-form-urlencoded"),
    );

    let mut form = HashMap::new();
    form.insert("channel", "C12345678");
    form.insert("text", "Hello from cURL");

    let response = client
        .post("https://slack.com/api/chat.postMessage")
        .headers(headers)
        .form(&form)
        .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;
using System.Text.Json;

class Program
{
    static async Task Main()
    {
        var token = Environment.GetEnvironmentVariable("SLACK_BOT_TOKEN");
        if (string.IsNullOrEmpty(token))
        {
            Console.Error.WriteLine("SLACK_BOT_TOKEN environment variable not set");
            return;
        }

        using var client = new HttpClient();
        client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);

        var form = new Dictionary<string, string>
        {
            { "channel", "C12345678" },
            { "text", "Hello from cURL" }
        };

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

        if (!response.IsSuccessStatusCode)
        {
            Console.Error.WriteLine($"HTTP error! status: {response.StatusCode}");
            return;
        }

        var json = await response.Content.ReadAsStringAsync();
        var result = JsonSerializer.Deserialize<System.Text.Json.JsonElement>(json);
        Console.WriteLine(result);
    }
}

Translation notes

  • All implementations use the idiomatic HTTP client for each language.
  • Bearer token is read from environment variable SLACK_BOT_TOKEN to avoid hardcoding.
  • Form data is sent as application/x-www-form-urlencoded as in the original cURL.
  • Error handling checks HTTP status and raises/logs errors if not successful.
  • JSON responses are parsed into native objects/dictionaries where applicable.

Common pitfalls when porting

  • Forgetting to set Content-Type header for form data in languages where it's not automatic.
  • Not properly URL-encoding form data in languages that don't handle it automatically.
  • Ignoring SSL/TLS verification in Go or other low-level clients.
  • Assuming JSON responses are always valid without error checking.
  • Hardcoding tokens in 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 tokens instead of hardcoding?

Environment variables prevent tokens from being committed to version control or exposed in logs, following security best practices.

How do I handle pagination or large responses?

Most HTTP clients provide streaming or chunked response handling. For example, in Python's requests you can use response.iter_content(), and in Go you can use io.Copy().

What if I need to send a JSON body instead of form data?

Replace the form data with a JSON object and set Content-Type to application/json. Example in Python: requests.post(url, json={'channel': 'C12345678', 'text': 'Hello'}).