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/files.sharedPublicURL \
  -H "Authorization: Bearer xoxp-1234567890-1234567890-1234567890-12345" \
  -d '{"file":"F1234567890"}'

Python · requests

import os
import requests

response = requests.post(
    "https://slack.com/api/files.sharedPublicURL",
    headers={"Authorization": f"Bearer {os.environ['SLACK_BEARER_TOKEN']}"},
    json={"file": "F1234567890"}
)
response.raise_for_status()
print(response.json())

Python · httpx

import os
import httpx

response = httpx.post(
    "https://slack.com/api/files.sharedPublicURL",
    headers={"Authorization": f"Bearer {os.environ['SLACK_BEARER_TOKEN']}"},
    json={"file": "F1234567890"}
)
response.raise_for_status()
print(response.json())

Node.js · fetch

import fetch from 'node-fetch';

const response = await fetch('https://slack.com/api/files.sharedPublicURL', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${process.env.SLACK_BEARER_TOKEN}`
  },
  body: JSON.stringify({"file": "F1234567890"})
});

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/files.sharedPublicURL',
  {"file": "F1234567890"},
  {
    headers: {
      'Authorization': `Bearer ${process.env.SLACK_BEARER_TOKEN}`
    }
  }
);

console.log(response.data);

Go · net/http

package main

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

type RequestBody struct {
	File string `json:"file"`
}

func main() {
	client := &http.Client{}
	url := "https://slack.com/api/files.sharedPublicURL"
	
	body := RequestBody{File: "F1234567890"}
	jsonBody, err := json.Marshal(body)
	if err != nil {
		log.Fatal(err)
	}
	
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonBody))
	if err != nil {
		log.Fatal(err)
	}
	
	req.Header.Set("Authorization", "Bearer "+os.Getenv("SLACK_BEARER_TOKEN"))
	req.Header.Set("Content-Type", "application/json")
	
	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, body)
	}
	
	var result map[string]interface{}
	if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
		log.Fatal(err)
	}
	
	fmt.Println(result)
}

PHP · cURL

<?php

$ch = curl_init('https://slack.com/api/files.sharedPublicURL');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['file' => 'F1234567890']));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Authorization: Bearer ' . getenv('SLACK_BEARER_TOKEN'),
    'Content-Type: application/json'
]);

$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");
}

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

curl_close($ch);

Ruby · net/http

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

uri = URI.parse('https://slack.com/api/files.sharedPublicURL')
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_BEARER_TOKEN']}"
request['Content-Type'] = 'application/json'
request.body = {file: 'F1234567890'}.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/files.sharedPublicURL")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Bearer \(ProcessInfo.processInfo.environment["SLACK_BEARER_TOKEN"] ?? "")", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

let body: [String: Any] = ["file": "F1234567890"]
request.httpBody = try? JSONSerialization.data(withJSONObject: body)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    if let error = error {
        fatalError(error.localizedDescription)
    }
    
    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 reqwest::blocking::Client;
use std::env;

fn main() {
    let client = Client::new();
    let url = "https://slack.com/api/files.sharedPublicURL";
    let bearer_token = env::var("SLACK_BEARER_TOKEN").expect("SLACK_BEARER_TOKEN must be set");
    
    let response = client
        .post(url)
        .header("Authorization", format!("Bearer {}", bearer_token))
        .json(&serde_json::json!({"file": "F1234567890"}))
        .send()
        .expect("Failed to send request");
    
    if !response.status().is_success() {
        panic!("HTTP error! status: {}", response.status());
    }
    
    let body = response.json::<serde_json::Value>().expect("Failed to parse response");
    println!("{:?}", body);
}

C# · HttpClient

using System;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        var client = new HttpClient();
        var url = "https://slack.com/api/files.sharedPublicURL";
        var bearerToken = Environment.GetEnvironmentVariable("SLACK_BEARER_TOKEN");
        
        var requestBody = new { file = "F1234567890" };
        var content = new StringContent(JsonSerializer.Serialize(requestBody), System.Text.Encoding.UTF8, "application/json");
        
        client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", bearerToken);
        
        var response = await client.PostAsync(url, content);
        
        if (!response.IsSuccessStatusCode)
        {
            throw new Exception($"HTTP error! status: {response.StatusCode}");
        }
        
        var responseBody = await response.Content.ReadAsStringAsync();
        var result = JsonSerializer.Deserialize<System.Text.Json.JsonElement>(responseBody);
        Console.WriteLine(result);
    }
}

Translation notes

  • All implementations use the idiomatic HTTP client for each language.
  • Bearer token is read from environment variables (SLACK_BEARER_TOKEN) to avoid hardcoding.
  • JSON bodies are sent as structured objects, not raw strings.
  • Error handling checks HTTP status and raises exceptions on failure.
  • Content-Type header is set to 'application/json' for JSON bodies.

Common pitfalls when porting

  • Forgetting to set the Content-Type header may cause the server to reject the request.
  • Not reading the response body on error can obscure the actual error message.
  • In Go, forgetting to close the response body can lead to resource leaks.
  • In Swift, the URLSession task runs asynchronously; ensure proper handling in real applications.
  • In Rust, using blocking client may not be suitable for async applications; consider reqwest::Client with async/await.

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 as they avoid hardcoding sensitive data in source code and can be managed separately from the application code.

How do I handle pagination or large responses?

Most HTTP libraries provide streaming or chunked response handling. For example, in Python's requests, use `response.iter_content()` for large files.

Can I use a different JSON library?

Yes, but ensure it properly serializes the body and deserializes the response. Popular alternatives include `orjson` in Python or `serde_json` in Rust.