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 \
  -H "Authorization: Bearer xoxb-1234567890" \
  -F file=@document.pdf \
  -F channels=C12345678

Python · requests

import os
import requests

url = "https://slack.com/api/files.upload"
headers = {
    "Authorization": f"Bearer {os.environ['SLACK_BOT_TOKEN']}"
}
files = {
    "file": open("document.pdf", "rb")
}
form_data = {
    "channels": "C12345678"
}

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

Python · httpx

import os
import httpx

url = "https://slack.com/api/files.upload"
headers = {
    "Authorization": f"Bearer {os.environ['SLACK_BOT_TOKEN']}"
}
files = {
    "file": open("document.pdf", "rb")
}
form_data = {
    "channels": "C12345678"
}

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

Node.js · fetch

import { readFileSync } from 'fs';
import fetch from 'node-fetch';

const url = 'https://slack.com/api/files.upload';
const headers = {
  'Authorization': `Bearer ${process.env.SLACK_BOT_TOKEN}`
};
const formData = new FormData();
formData.append('file', readFileSync('document.pdf'));
formData.append('channels', 'C12345678');

fetch(url, {
  method: 'POST',
  headers,
  body: formData
})
  .then(res => res.json())
  .then(console.log)
  .catch(console.error);

Node.js · axios

import axios from 'axios';
import FormData from 'form-data';
import { readFileSync } from 'fs';

const url = 'https://slack.com/api/files.upload';
const headers = {
  'Authorization': `Bearer ${process.env.SLACK_BOT_TOKEN}`
};
const form = new FormData();
form.append('file', readFileSync('document.pdf'));
form.append('channels', 'C12345678');

axios.post(url, form, { headers: { ...headers, ...form.getHeaders() } })
  .then(res => console.log(res.data))
  .catch(err => console.error(err));

Go · net/http

package main

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

func main() {
	url := "https://slack.com/api/files.upload"
	token := os.Getenv("SLACK_BOT_TOKEN")
	
	body := &bytes.Buffer{}
	writer := multipart.NewWriter(body)
	
	file, err := os.Open("document.pdf")
	if err != nil {
		panic(err)
	}
	defer file.Close()
	
	part, err := writer.CreateFormFile("file", "document.pdf")
	if err != nil {
		panic(err)
	}
	_, err = io.Copy(part, file)
	if err != nil {
		panic(err)
	}
	
	_ = writer.WriteField("channels", "C12345678")
	writer.Close()
	
	req, err := http.NewRequest("POST", url, body)
	if err != nil {
		panic(err)
	}
	req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
	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(fmt.Sprintf("unexpected status: %s", resp.Status))
	}
	
	fmt.Println(resp.Body)
}

PHP · cURL

<?php

$url = 'https://slack.com/api/files.upload';
$token = getenv('SLACK_BOT_TOKEN');

$client = new CURLFile('document.pdf', 'application/pdf', 'document.pdf');
$post = [
    'file' => $client,
    'channels' => 'C12345678'
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Authorization: Bearer ' . $token
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);
if (curl_errno($ch)) {
    die(curl_error($ch));
}
curl_close($ch);

print_r(json_decode($response, true));

Ruby · net/http

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

url = URI.parse('https://slack.com/api/files.upload')
token = ENV['SLACK_BOT_TOKEN']

file_path = 'document.pdf'
file = File.open(file_path, 'rb')

req = Net::HTTP::Post::Multipart.new(url.path, {
  file: UploadIO.new(file, MIME::Types.type_for(file_path).first.to_s, file_path),
  channels: 'C12345678'
})

req['Authorization'] = "Bearer #{token}"

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

response = http.request(req)
puts response.body

Swift · URLSession

import Foundation

let url = URL(string: "https://slack.com/api/files.upload")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Bearer \(ProcessInfo.processInfo.environment["SLACK_BOT_TOKEN"] ?? "")", forHTTPHeaderField: "Authorization")

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

var body = Data()

let fileData = try Data(contentsOf: URL(fileURLWithPath: "document.pdf"))
body.append("--\(boundary)\r\n".data(using: .utf8)!)
body.append("Content-Disposition: form-data; name=\"file\"; filename=\"document.pdf\"\r\n".data(using: .utf8)!)
body.append("Content-Type: application/pdf\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)!)
body.append("Content-Disposition: form-data; name=\"channels\"\r\n\r\n".data(using: .utf8)!)
body.append("C12345678\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 {
        print(error)
        return
    }
    guard let data = data else {
        print("No data received")
        return
    }
    if 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;
use std::fs::File;
use std::io::Read;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let url = "https://slack.com/api/files.upload";
    let token = env::var("SLACK_BOT_TOKEN")?;

    let mut file = File::open("document.pdf")?;
    let mut buffer = Vec::new();
    file.read_to_end(&mut buffer)?;

    let form = reqwest::blocking::multipart::Form::new()
        .file("file", "document.pdf")?
        .text("channels", "C12345678");

    let client = Client::new();
    let response = client
        .post(url)
        .header("Authorization", format!("Bearer {}", token))
        .multipart(form)
        .send()?;

    if !response.status().is_success() {
        return Err(format!("Request failed: {}", response.status()).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 url = "https://slack.com/api/files.upload";
        var token = Environment.GetEnvironmentVariable("SLACK_BOT_TOKEN");

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

        var fileStream = File.OpenRead("document.pdf");
        var streamContent = new StreamContent(fileStream);
        var fileContent = new ByteArrayContent(await streamContent.ReadAsByteArrayAsync());
        fileContent.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/pdf");
        form.Add(fileContent, "file", "document.pdf");

        form.Add(new StringContent("C12345678"), "channels");

        client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);

        var response = await client.PostAsync(url, form);
        response.EnsureSuccessStatusCode();

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

Translation notes

  • All implementations use environment variables for the bearer token (SLACK_BOT_TOKEN).
  • Python, Node.js, Go, Ruby, Rust, and C# use idiomatic multipart/form-data libraries.
  • PHP uses CURLFile for file uploads in multipart requests.
  • Swift uses URLSession with manual multipart form construction.
  • Error handling is minimal but includes status code checks and basic error propagation.

Common pitfalls when porting

  • Forgetting to close file handles in Python, Go, or Ruby can lead to resource leaks.
  • In Node.js, forgetting to set the Content-Type header for multipart requests may cause issues.
  • In Go, not setting the Content-Type header with the boundary can break the request.
  • In Swift, not running the URLSession task in a run loop can cause the program to exit before completion.
  • In Rust, using async reqwest requires a runtime (e.g., tokio) for non-blocking 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 the token instead of hardcoding?

Environment variables prevent accidental exposure of secrets in version control or logs. They also allow configuration without code changes.

How do I handle large file uploads efficiently?

Stream the file content instead of reading it entirely into memory. Most libraries (e.g., Python requests, Go, Rust) support streaming.

Can I use a different HTTP client library?

Yes, but ensure it supports multipart/form-data and bearer token authentication. Popular alternatives include Python's httpx, Node.js's got, and Go's fasthttp.