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.create -H "Authorization: Bearer xoxb-1234567890-1234567890123-abcdefghijklmnopqrstuvwxyz" -d '{"name":"new-channel","is_private":false}'

Python · requests

import os
import requests

url = "https://slack.com/api/conversations.create"
headers = {
    "Authorization": f"Bearer {os.environ['SLACK_BOT_TOKEN']}"
}
data = {
    "name": "new-channel",
    "is_private": False
}

response = requests.post(url, headers=headers, json=data)
if response.status_code != 200:
    raise Exception(f"Request failed with status {response.status_code}")
print(response.json())

Python · httpx

import os
import httpx

url = "https://slack.com/api/conversations.create"
headers = {
    "Authorization": f"Bearer {os.environ['SLACK_BOT_TOKEN']}"
}
data = {
    "name": "new-channel",
    "is_private": False
}

with httpx.Client() as client:
    response = client.post(url, headers=headers, json=data)
    if response.status_code != 200:
        raise Exception(f"Request failed with status {response.status_code}")
    print(response.json())

Node.js · fetch

import fetch from 'node-fetch';
import { config } from 'dotenv';

config();

const url = 'https://slack.com/api/conversations.create';
const headers = {
  'Authorization': `Bearer ${process.env.SLACK_BOT_TOKEN}`
};
const body = JSON.stringify({
  name: 'new-channel',
  is_private: false
});

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

Node.js · axios

import axios from 'axios';
import { config } from 'dotenv';

config();

const url = 'https://slack.com/api/conversations.create';
const headers = {
  'Authorization': `Bearer ${process.env.SLACK_BOT_TOKEN}`
};
const data = {
  name: 'new-channel',
  is_private: false
};

axios.post(url, data, { headers })
  .then(res => {
    if (res.status !== 200) throw new Error(`Request failed with status ${res.status}`);
    console.log(res.data);
  })
  .catch(console.error);

Go · net/http

package main

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

func main() {
	url := "https://slack.com/api/conversations.create"
	token := os.Getenv("SLACK_BOT_TOKEN")
	if token == "" {
		panic("SLACK_BOT_TOKEN environment variable not set")
	}

	body := map[string]interface{}{
		"name":        "new-channel",
		"is_private": false,
	}
	jsonBody, _ := json.Marshal(body)

	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonBody))
	if err != nil {
		panic(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 {
		panic(err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		body, _ := io.ReadAll(resp.Body)
		panic(fmt.Sprintf("Request failed with status %d: %s", resp.StatusCode, string(body)))
	}

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

PHP · cURL

<?php

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

$headers = [
    'Authorization: Bearer ' . $token,
    'Content-Type: application/json'
];

$data = [
    'name' => 'new-channel',
    'is_private' => false
];

$options = [
    'http' => [
        'header' => $headers,
        'method' => 'POST',
        'content' => json_encode($data),
        'ignore_errors' => true
    ]
];

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

if ($http_response_header[0] !== 'HTTP/1.1 200 OK') {
    die('Request failed with status ' . $http_response_header[0]);
}

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

Ruby · net/http

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

url = URI.parse('https://slack.com/api/conversations.create')
token = ENV.fetch('SLACK_BOT_TOKEN')

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 = { name: 'new-channel', is_private: false }.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

let url = URL(string: "https://slack.com/api/conversations.create")!
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] = [
    "name": "new-channel",
    "is_private": false
]

request.httpBody = try? JSONSerialization.data(withJSONObject: body)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    guard let data = data, error == nil else {
        fatalError("Request failed: \(error?.localizedDescription ?? "Unknown error")")
    }

    guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
        fatalError("Request failed with status \((response as? HTTPURLResponse)?.statusCode ?? 0)")
    }

    if 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/conversations.create";
    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 body: HashMap<&str, serde_json::Value> = HashMap::from([
        ("name", serde_json::Value::String("new-channel".to_string())),
        ("is_private", serde_json::Value::Bool(false)),
    ]);

    let client = Client::new();
    let response = client
        .post(url)
        .headers(headers)
        .json(&body)
        .send()?;

    if !response.status().is_success() {
        return Err(format!("Request failed with 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/conversations.create";
        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();
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

        var body = new Dictionary<string, object>
        {
            { "name", "new-channel" },
            { "is_private", false }
        };

        var response = await client.PostAsJsonAsync(url, body);
        if (!response.IsSuccessStatusCode)
        {
            throw new Exception($"Request failed with status {response.StatusCode}");
        }

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

Translation notes

  • All implementations use environment variables for secrets (SLACK_BOT_TOKEN)
  • Python, Node.js, and Ruby examples use async/await or promises where idiomatic
  • Go and Rust examples use blocking clients for simplicity (non-blocking examples would be longer)
  • PHP uses file_get_contents with stream context for simplicity
  • Swift uses URLSession with async/await (requires Swift 5.5+)
  • C# uses HttpClient with async/await
  • Error handling checks status code and raises exceptions where appropriate

Common pitfalls when porting

  • Forgetting to set the Content-Type header to application/json in languages that don't infer it
  • Not properly escaping JSON body in languages that don't automatically serialize objects
  • Ignoring SSL certificate validation in Go/Rust examples
  • Assuming synchronous HTTP clients are always acceptable (they block the thread)
  • Not handling environment variable absence gracefully

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, making it easier to manage secrets and avoid accidental commits to version control.

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

These examples focus on the basic request. For pagination/rate limits, you'd need to inspect response headers and implement retry logic with exponential backoff.

Can I use these examples in production without modification?

These are minimal examples. Production code should include proper logging, retry policies, circuit breakers, and more robust error handling.