Qaynaq LABS · TOOLS

CURL → CODE · POST · BEARER

cURL → 10 languages

POST slack.com · body: multipart · secrets replaced with env vars.

Source cURL
curl -X POST https://slack.com/api/files.upload \
  -F "token=xoxb-1234567890-123456789012-abcdefghijklmnopqrstuvwx" \
  -F "channels=C1234567890" \
  -F "file=@/path/to/file.txt;type=text/plain"

Python · requests

import os
import requests

response = requests.post(
    "https://slack.com/api/files.upload",
    files={"file": open("/path/to/file.txt", "rb")},
    data={
        "token": os.environ["SLACK_TOKEN"],
        "channels": os.environ["SLACK_CHANNELS"]
    }
)
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/files.upload",
        files={"file": open("/path/to/file.txt", "rb")},
        data={
            "token": os.environ["SLACK_TOKEN"],
            "channels": os.environ["SLACK_CHANNELS"]
        }
    )
    response.raise_for_status()
    print(response.json())

Node.js · fetch

import fetch from 'node-fetch';
import fs from 'fs';
import { env } from 'process';

const response = await fetch('https://slack.com/api/files.upload', {
  method: 'POST',
  body: new FormData()
    .append('token', env.SLACK_TOKEN)
    .append('channels', env.SLACK_CHANNELS)
    .append('file', fs.createReadStream('/path/to/file.txt'), {
      filename: 'file.txt',
      contentType: 'text/plain'
    }),
});
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';
import fs from 'fs';
import { env } from 'process';

const response = await axios.post(
  'https://slack.com/api/files.upload',
  new FormData()
    .append('token', env.SLACK_TOKEN)
    .append('channels', env.SLACK_CHANNELS)
    .append('file', fs.createReadStream('/path/to/file.txt'), {
      filename: 'file.txt',
      contentType: 'text/plain'
    })
);
console.log(response.data);

Go · net/http

package main

import (
	"bytes"
	"io"
	"mime/multipart"
	"net/http"
	"os"
)

func main() {
	token := os.Getenv("SLACK_TOKEN")
	channels := os.Getenv("SLACK_CHANNELS")

	body := &bytes.Buffer{}
	writer := multipart.NewWriter(body)

	_ = writer.WriteField("token", token)
	_ = writer.WriteField("channels", channels)

	file, err := os.Open("/path/to/file.txt")
	if err != nil {
		panic(err)
	}
	defer file.Close()

	part, err := writer.CreateFormFile("file", "file.txt")
	if err != nil {
		panic(err)
	}
	_, err = io.Copy(part, file)
	if err != nil {
		panic(err)
	}

	_ = writer.Close()

	req, err := http.NewRequest("POST", "https://slack.com/api/files.upload", body)
	if err != nil {
		panic(err)
	}
	req.Header.Set("Content-Type", writer.FormDataContentType())

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		panic("request failed")
	}

	// Read response body
	// ...
}

PHP · cURL

<?php
$token = getenv('SLACK_TOKEN');
$channels = getenv('SLACK_CHANNELS');

$client = new CURLClient();
$client->setOption(CURLOPT_URL, 'https://slack.com/api/files.upload');
$client->setOption(CURLOPT_POST, true);
$client->setOption(CURLOPT_POSTFIELDS, [
    'token' => $token,
    'channels' => $channels,
    'file' => new CURLFile('/path/to/file.txt', 'text/plain', 'file.txt')
]);
$response = $client->execute();
if ($response === false) {
    throw new Exception('Request failed');
}
$httpCode = $client->getInfo(CURLINFO_HTTP_CODE);
if ($httpCode !== 200) {
    throw new Exception("HTTP error: $httpCode");
}
$data = json_decode($response, true);
print_r($data);
$client->close();

Ruby · net/http

require 'net/http'
require 'uri'
require 'mime/types'

token = ENV['SLACK_TOKEN']
channels = ENV['SLACK_CHANNELS']

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

request = Net::HTTP::Post::Multipart.new(uri.path, {
  'token' => token,
  'channels' => channels,
  'file' => UploadIO.new(File.open('/path/to/file.txt'), 'text/plain', 'file.txt')
})

response = http.request(request)
unless response.is_a?(Net::HTTPSuccess)
  raise "HTTP error: #{response.code}"
end
puts JSON.parse(response.body)

Swift · URLSession

import Foundation

let token = ProcessInfo.processInfo.environment["SLACK_TOKEN"] ?? ""
let channels = ProcessInfo.processInfo.environment["SLACK_CHANNELS"] ?? ""

let url = URL(string: "https://slack.com/api/files.upload")!
var request = URLRequest(url: url)
request.httpMethod = "POST"

let boundary = UUID().uuidString
request.setValue("multipart/form-data; boundary=--\(boundary)", forHTTPHeaderField: "Content-Type")

var body = Data()

body.append("--\(boundary)\r\n".data(using: .utf8)!)
body.append("Content-Disposition: form-data; name=\"token\"\r\n\r\n".data(using: .utf8)!)
body.append(token.data(using: .utf8)!)
body.append("\r\n".data(using: .utf8)!)

body.append("--\(boundary)\r\n".data(using: .utf8)!)
body.append("Content-Disposition: form-data; name=\"channels\"\r\n\r\n".data(using: .utf8)!)
body.append(channels.data(using: .utf8)!)
body.append("\r\n".data(using: .utf8)!)

let fileData = try Data(contentsOf: URL(fileURLWithPath: "/path/to/file.txt"))
body.append("--\(boundary)\r\n".data(using: .utf8)!)
body.append("Content-Disposition: form-data; name=\"file\"; filename=\"file.txt\"\r\n".data(using: .utf8)!)
body.append("Content-Type: text/plain\r\n\r\n".data(using: .utf8)!)
body.append(fileData)
body.append("\r\n".data(using: .utf8)!)

body.append("--\(boundary)--\r\n".data(using: .utf8)!)

request.httpBody = 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, httpResponse.statusCode == 200 else {
        fatalError("HTTP error")
    }
    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::env;
use std::fs::File;
use std::io::Read;
use reqwest::multipart;
use reqwest::blocking::Client;

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

    let client = Client::new();
    let file = File::open("/path/to/file.txt")?;

    let form = multipart::Form::new()
        .file("file", "/path/to/file.txt")?
        .text("token", token)
        .text("channels", channels);

    let response = client
        .post("https://slack.com/api/files.upload")
        .multipart(form)
        .send()?;

    if !response.status().is_success() {
        return Err("Request failed".into());
    }

    let body = response.text()?;
    println!("{}", body);
    Ok(())
}

C# · HttpClient

using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        var token = Environment.GetEnvironmentVariable("SLACK_TOKEN");
        var channels = Environment.GetEnvironmentVariable("SLACK_CHANNELS");

        using var client = new HttpClient();
        using var form = new MultipartFormDataContent();

        var fileContent = new StreamContent(File.OpenRead("/path/to/file.txt"));
        fileContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("text/plain");
        form.Add(new StringContent(token), "token");
        form.Add(new StringContent(channels), "channels");
        form.Add(fileContent, "file", "file.txt");

        var response = await client.PostAsync("https://slack.com/api/files.upload", form);
        if (!response.IsSuccessStatusCode)
        {
            throw new Exception("Request failed");
        }

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

Translation notes

  • All implementations use environment variables for secrets (SLACK_TOKEN, SLACK_CHANNELS).
  • Python, Node.js, Go, Ruby, Swift, Rust, and C# use idiomatic HTTP clients with multipart form support.
  • PHP uses CURL directly for multipart form data with CURLFile.
  • Error handling checks HTTP status and raises exceptions on failure.
  • File uploads are handled via file streams or direct file reads.

Common pitfalls when porting

  • Forgetting to set Content-Type header for multipart requests in low-level clients.
  • Not properly closing file handles or streams in languages requiring explicit cleanup.
  • Assuming the response body is always JSON without checking Content-Type.
  • Hardcoding file paths or tokens instead of using environment variables.
  • Ignoring SSL/TLS verification in Go or other languages with custom HTTP clients.

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 separate configuration from code, reducing the risk of accidental exposure in version control or logs.

How do I handle large file uploads efficiently?

Use streaming APIs (e.g., file streams in Python, Node.js, or Rust) to avoid loading the entire file into memory.

Can I use a different HTTP client library?

Yes, but ensure it supports multipart form data and streaming uploads for large files.