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-abcdefghijklmnopqrstuvwx" \
  -H "Content-Type: application/json" \
  -d '{"channel":"C1234567890","text":"Hello from curl!"}'

Python · requests

import os
import requests

url = "https://slack.com/api/chat.postMessage"
headers = {
    "Authorization": f"Bearer {os.environ['SLACK_BOT_TOKEN']}",
    "Content-Type": "application/json"
}
data = {
    "channel": "C1234567890",
    "text": "Hello from curl!"
}

response = requests.post(url, headers=headers, json=data)
response.raise_for_status()
print(response.json())

Python · httpx

import os
import httpx

url = "https://slack.com/api/chat.postMessage"
headers = {
    "Authorization": f"Bearer {os.environ['SLACK_BOT_TOKEN']}",
    "Content-Type": "application/json"
}
data = {
    "channel": "C1234567890",
    "text": "Hello from curl!"
}

with httpx.Client() as client:
    response = client.post(url, headers=headers, json=data)
    response.raise_for_status()
    print(response.json())

Node.js · fetch

import fetch from 'node-fetch';

const url = 'https://slack.com/api/chat.postMessage';
const headers = {
  'Authorization': `Bearer ${process.env.SLACK_BOT_TOKEN}`,
  'Content-Type': 'application/json'
};
const data = {
  channel: 'C1234567890',
  text: 'Hello from curl!'
};

fetch(url, {
  method: 'POST',
  headers,
  body: JSON.stringify(data)
})
  .then(res => {
    if (!res.ok) throw new Error(`HTTP error! status: ${res.status}`);
    return res.json();
  })
  .then(console.log)
  .catch(console.error);

Node.js · axios

import axios from 'axios';

const url = 'https://slack.com/api/chat.postMessage';
const headers = {
  'Authorization': `Bearer ${process.env.SLACK_BOT_TOKEN}`,
  'Content-Type': 'application/json'
};
const data = {
  channel: 'C1234567890',
  text: 'Hello from curl!'
};

axios.post(url, data, { headers })
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error('Error:', error.message);
  });

Go · net/http

package main

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

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

func main() {
	url := "https://slack.com/api/chat.postMessage"
	token := os.Getenv("SLACK_BOT_TOKEN")
	if token == "" {
		log.Fatal("SLACK_BOT_TOKEN environment variable not set")
	}

	data := Message{
		Channel: "C1234567890",
		Text:    "Hello from curl!",
	}
	body, err := json.Marshal(data)
	if err != nil {
		log.Fatal(err)
	}

	req, err := http.NewRequest("POST", url, 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 {
		body, _ := io.ReadAll(resp.Body)
		log.Fatalf("HTTP error! status: %s, body: %s", resp.Status, string(body))
	}

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

PHP · cURL

<?php

$url = 'https://slack.com/api/chat.postMessage';
$token = getenv('SLACK_BOT_TOKEN');
if (empty($token)) {
    die('SLACK_BOT_TOKEN environment variable not set');
}

$data = [
    'channel' => 'C1234567890',
    'text' => 'Hello from curl!'
];

$options = [
    'http' => [
        'header' => [
            "Authorization: Bearer $token",
            "Content-Type: application/json"
        ],
        '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'

url = URI.parse('https://slack.com/api/chat.postMessage')
token = ENV.fetch('SLACK_BOT_TOKEN') { raise 'SLACK_BOT_TOKEN environment variable not set' }

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url.path)
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 error! status: #{response.code}"
end

puts JSON.parse(response.body)

Swift · URLSession

import Foundation

let url = URL(string: "https://slack.com/api/chat.postMessage")!
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: 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 {
        print("Error: \(error)")
        return
    }
    guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
        print("HTTP error! status: \((response as? HTTPURLResponse)?.statusCode ?? 0)")
        return
    }
    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 url = "https://slack.com/api/chat.postMessage";
    let token = env::var("SLACK_BOT_TOKEN")?;

    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/json"),
    );

    let mut body = HashMap::new();
    body.insert("channel", "C1234567890");
    body.insert("text", "Hello from curl!");

    let client = Client::new();
    let response = client
        .post(url)
        .headers(headers)
        .json(&body)
        .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.Net.Http.Headers;
using System.Text.Json;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        var url = "https://slack.com/api/chat.postMessage";
        var token = Environment.GetEnvironmentVariable("SLACK_BOT_TOKEN");
        if (string.IsNullOrEmpty(token))
        {
            Console.WriteLine("SLACK_BOT_TOKEN environment variable not set");
            return;
        }

        var client = new HttpClient();
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        var body = new Dictionary<string, string>
        {
            { "channel", "C1234567890" },
            { "text", "Hello from curl!" }
        };

        var response = await client.PostAsJsonAsync(url, body);
        if (!response.IsSuccessStatusCode)
        {
            Console.WriteLine($"HTTP error! status: {response.StatusCode}");
            return;
        }

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

Translation notes

  • All implementations use the idiomatic HTTP client for each language.
  • Bearer token is read from environment variables (SLACK_BOT_TOKEN).
  • Error handling checks HTTP status and reads response body.
  • JSON bodies are sent as structured objects, not raw strings.
  • Minimal dependencies: only standard libraries or widely-used HTTP clients.

Common pitfalls when porting

  • Forgetting to set the Content-Type header to application/json.
  • Not handling environment variable absence (SLACK_BOT_TOKEN).
  • Ignoring HTTP status codes in responses.
  • Using raw strings for JSON bodies instead of structured objects.
  • Not using HTTPS for production requests.

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 are a secure way to handle secrets, avoiding hardcoding in source code. They can be managed by deployment systems or secrets managers.

Can I use a different HTTP client library?

Yes, but ensure it supports the same features (headers, JSON bodies, HTTPS, status checks).

How do I handle pagination or retries?

Add retry logic and pagination handling based on the API's requirements. Most HTTP clients support interceptors or middleware for this.