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/chat.postMessage -H "Authorization: Bearer xoxb-1234567890-1234567890123-abcdefghijklmnopqrstuvwxyz" -d '{"channel":"C1234567890","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']}"},
    json={"channel": "C1234567890", "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']}"},
    json={"channel": "C1234567890", "text": "Hello from curl!"}
)
response.raise_for_status()
print(response.json())

Node.js · fetch

import fetch from 'node-fetch';

const response = await fetch('https://slack.com/api/chat.postMessage', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${process.env.SLACK_BOT_TOKEN}`,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({"channel": "C1234567890", "text": "Hello from curl!"})
});

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/chat.postMessage',
  {"channel": "C1234567890", "text": "Hello from curl!"},
  {
    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"
)

type Message struct {
	Channel string `json:"channel"`
	Text    string `json:"text"`
}

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

	msg := Message{Channel: "C1234567890", Text: "Hello from curl!"}
	body, _ := json.Marshal(msg)

	req, err := http.NewRequest(
		"POST",
		"https://slack.com/api/chat.postMessage",
		bytes.NewBuffer(body),
	)
	if err != nil {
		log.Fatal(err)
	}

	req.Header.Set("Authorization", "Bearer "+token)
	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: %s", resp.Status)
	}

	var result map[string]interface{}
	json.NewDecoder(resp.Body).Decode(&result)
	fmt.Println(result)
}

PHP · cURL

<?php

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

$url = 'https://slack.com/api/chat.postMessage';
$data = [
    'channel' => 'C1234567890',
    'text' => 'Hello from curl!'
];

$options = [
    'http' => [
        'header' => "Authorization: Bearer $token\r\nContent-Type: application/json\r\n",
        'method' => 'POST',
        'content' => json_encode($data)
    ]
];

$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);

if ($result === false) {
    die('Request failed');
}

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

Ruby · net/http

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

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['Content-Type'] = 'application/json'
request.body = { channel: 'C1234567890', text: 'Hello from curl!' }.to_json

response = http.request(request)

unless response.is_a?(Net::HTTPSuccess)
  raise "HTTP request failed: #{response.code} #{response.message}"
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/json", forHTTPHeaderField: "Content-Type")

let body: [String: Any] = ["channel": "C1234567890", "text": "Hello from curl!"]
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,
          (200...299).contains(httpResponse.statusCode) else {
        fatalError("Request failed with 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 reqwest::blocking::Client;
use serde_json::json;
use std::env;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let token = env::var("SLACK_BOT_TOKEN")?;

    let client = Client::new();
    let response = client
        .post("https://slack.com/api/chat.postMessage")
        .header("Authorization", format!("Bearer {}", token))
        .json(&json!({"channel": "C1234567890", "text": "Hello from curl!"}))
        .send()?;

    if !response.status().is_success() {
        return Err(format!("Request failed with 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 token = Environment.GetEnvironmentVariable("SLACK_BOT_TOKEN");
        if (string.IsNullOrEmpty(token))
        {
            Console.WriteLine("SLACK_BOT_TOKEN environment variable not set");
            return;
        }

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

        var message = new { channel = "C1234567890", text = "Hello from curl!" };
        var content = new StringContent(JsonSerializer.Serialize(message));
        content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

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

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

Translation notes

  • All implementations use the idiomatic HTTP client for each language
  • Bearer token is read from environment variable SLACK_BOT_TOKEN
  • JSON body is constructed as a native object/dict
  • Error handling checks HTTP status and reads response body
  • Content-Type header is set to application/json where required
  • Python implementations use requests and httpx, both popular choices

Common pitfalls when porting

  • Forgetting to set Content-Type header in languages that don't auto-set it
  • Not properly escaping JSON body content in raw HTTP clients
  • Assuming environment variables are always set (always validate)
  • Ignoring HTTP status codes in minimal error handling
  • Using string concatenation for tokens instead of f-strings/template literals
  • Not using HTTPS in Go's http.Client (use http.Client{Transport: &http.Transport{TLSHandshakeTimeout: 10*time.Second}} for production)

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 separate configuration from code, preventing accidental commits of secrets. They also allow different configurations across environments (dev, staging, prod).

How do I handle pagination or rate limits in these clients?

Most HTTP clients have built-in retry mechanisms. For Slack specifically, check the 'Retry-After' header and implement exponential backoff. Consider using a dedicated Slack SDK for advanced features.

Can I use async/await in all these languages?

Yes, but the synchronous examples are shown for simplicity. Most languages support both sync and async patterns. For production, async is preferred for I/O-bound operations.

What if I need to send file attachments?

Use multipart/form-data instead of JSON. Each language has different ways to construct multipart requests. For Slack specifically, use the 'files.upload' API endpoint.