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/users.admin.setInactive -H "Authorization: Bearer xoxb-1234567890-123456789012-abcdefghijklmnopqrstuvwx" -d "user=U12345678"

Python · requests

import os
import requests

response = requests.post(
    "https://slack.com/api/users.admin.setInactive",
    headers={"Authorization": f"Bearer {os.environ['SLACK_BOT_TOKEN']}"},
    data={"user": "U12345678"}
)
response.raise_for_status()
print(response.json())

Python · httpx

import os
import httpx

with httpx.Client() as client:
    response = client.post(
        "https://slack.com/api/users.admin.setInactive",
        headers={"Authorization": f"Bearer {os.environ['SLACK_BOT_TOKEN']}"},
        data={"user": "U12345678"}
    )
    response.raise_for_status()
    print(response.json())

Node.js · fetch

import fetch from 'node-fetch';

const response = await fetch('https://slack.com/api/users.admin.setInactive', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${process.env.SLACK_BOT_TOKEN}`
  },
  body: new URLSearchParams({
    user: 'U12345678'
  })
});

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/users.admin.setInactive',
  new URLSearchParams({
    user: 'U12345678'
  }),
  {
    headers: {
      'Authorization': `Bearer ${process.env.SLACK_BOT_TOKEN}`
    }
  }
);

console.log(response.data);

Go · net/http

package main

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

func main() {
	client := &http.Client{}
	form := url.Values{}
	form.Add("user", "U12345678")

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

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

	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: %d", resp.StatusCode))
	}

	// Handle response body as needed
}

PHP · cURL

<?php

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'https://slack.com/api/users.admin.setInactive');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(['user' => 'U12345678']));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Authorization: Bearer ' . getenv('SLACK_BOT_TOKEN')
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

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

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

curl_close($ch);

Ruby · net/http

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

uri = URI.parse('https://slack.com/api/users.admin.setInactive')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true

request = Net::HTTP::Post.new(uri.request_uri)
request['Authorization'] = "Bearer #{ENV['SLACK_BOT_TOKEN']}"
request.set_form_data({'user' => 'U12345678'})

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/users.admin.setInactive")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Bearer \(ProcessInfo.processInfo.environment["SLACK_BOT_TOKEN"] ?? "")", forHTTPHeaderField: "Authorization")
request.httpBody = URLComponents().queryItems = [URLQueryItem(name: "user", value: "U12345678")].map { $0.percentEncodedQuery ?? "" }.joined(separator: "&").data(using: .utf8)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    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 client = Client::new();
    let mut headers = header::HeaderMap::new();
    headers.insert(
        "Authorization",
        format!("Bearer {}", env::var("SLACK_BOT_TOKEN")?).parse()?,
    );

    let mut form = HashMap::new();
    form.insert("user", "U12345678");

    let response = client
        .post("https://slack.com/api/users.admin.setInactive")
        .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;

class Program
{
    static async Task Main()
    {
        var client = new HttpClient();
        var form = new Dictionary<string, string>
        {
            {"user", "U12345678"}
        };

        var request = new HttpRequestMessage(HttpMethod.Post, "https://slack.com/api/users.admin.setInactive")
        {
            Content = new FormUrlEncodedContent(form)
        };
        request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(
            "Bearer",
            Environment.GetEnvironmentVariable("SLACK_BOT_TOKEN")
        );

        var response = await client.SendAsync(request);
        if (!response.IsSuccessStatusCode)
        {
            throw new Exception($"HTTP error! status: {response.StatusCode}");
        }

        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 variable SLACK_BOT_TOKEN.
  • Form data is used for the request body (application/x-www-form-urlencoded).
  • Error handling checks HTTP status code and raises an exception if not 2xx.
  • JSON response is parsed and printed in each example.

Common pitfalls when porting

  • Forgetting to set the Content-Type header for form data (handled automatically by most clients).
  • Not handling environment variable absence (SLACK_BOT_TOKEN must be set).
  • Assuming the response body is always JSON (Slack API may return errors as plain text).
  • In Go, forgetting to set the Content-Type header explicitly (though most clients do this automatically).

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 form data instead of JSON for the request body?

The Slack API expects form-encoded data for this endpoint, not JSON. Using the correct content type is critical for API compatibility.

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

These examples focus on minimal error handling. For production, consider adding retry logic (e.g., with exponential backoff) and rate limit detection.

Can I use a different environment variable name for the token?

Yes, but ensure consistency across your codebase. Update the environment variable name in all implementations if changed.