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-1234567890123-abcdefghijklmnopqrstuvwx" \
  -F "file=@report.pdf" \
  -F "channels=C1234567890"

Python · requests

import os
import requests

response = requests.post(
    "https://slack.com/api/files.upload",
    headers={"Authorization": f"Bearer {os.environ['SLACK_BOT_TOKEN']}"},
    files={"file": open("report.pdf", "rb")},
    data={"channels": "C1234567890"}
)
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",
        headers={"Authorization": f"Bearer {os.environ['SLACK_BOT_TOKEN']}"},
        files={"file": open("report.pdf", "rb")},
        data={"channels": "C1234567890"}
    )
    response.raise_for_status()
    print(response.json())

Node.js · fetch

import fetch from 'node-fetch';
import fs from 'fs';
import { Buffer } from 'buffer';

const token = process.env.SLACK_BOT_TOKEN;
const file = fs.readFileSync('report.pdf');

const formData = new FormData();
formData.append('file', new Blob([file]), 'report.pdf');
formData.append('channels', 'C1234567890');

const response = await fetch('https://slack.com/api/files.upload', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${token}`,
  },
  body: formData,
});
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 FormData from 'form-data';

const token = process.env.SLACK_BOT_TOKEN;
const form = new FormData();
form.append('file', fs.createReadStream('report.pdf'));
form.append('channels', 'C1234567890');

const response = await axios.post('https://slack.com/api/files.upload', form, {
  headers: {
    ...form.getHeaders(),
    'Authorization': `Bearer ${token}`,
  },
});
console.log(response.data);

Go · net/http

package main

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

func main() {
	token := os.Getenv("SLACK_BOT_TOKEN")
	file, err := os.Open("report.pdf")
	if err != nil {
		panic(err)
	}
	defer file.Close()

	body := &bytes.Buffer{}
	writer := multipart.NewWriter(body)
	part, err := writer.CreateFormFile("file", "report.pdf")
	if err != nil {
		panic(err)
	}
	_, err = io.Copy(part, file)
	if err != nil {
		panic(err)
	}
	writer.WriteField("channels", "C1234567890")
	writer.Close()

	req, err := http.NewRequest("POST", "https://slack.com/api/files.upload", body)
	if err != nil {
		panic(err)
	}
	req.Header.Set("Authorization", "Bearer "+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("HTTP error! status: %s", resp.Status))
	}
	fmt.Println(resp.Body)
}

PHP · cURL

<?php
$token = getenv('SLACK_BOT_TOKEN');
$file = new CURLFile('report.pdf', 'application/pdf', 'report.pdf');

$post = [
    'file' => $file,
    'channels' => 'C1234567890',
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://slack.com/api/files.upload');
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)) {
    throw new Exception(curl_error($ch));
}
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode !== 200) {
    throw new Exception("HTTP error! status: $httpCode");
}
print_r(json_decode($response, true));
curl_close($ch);

Ruby · net/http

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

token = ENV['SLACK_BOT_TOKEN']
file_path = 'report.pdf'

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,
  'file' => UploadIO.new(File.open(file_path), MIME::Types.type_for(file_path).first.to_s, File.basename(file_path)),
  'channels' => 'C1234567890'
)
request['Authorization'] = "Bearer #{token}"

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 token = ProcessInfo.processInfo.environment["SLACK_BOT_TOKEN"] ?? ""
let fileURL = URL(fileURLWithPath: "report.pdf")
let boundary = UUID().uuidString
var request = URLRequest(url: URL(string: "https://slack.com/api/files.upload")!)
request.httpMethod = "POST"
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")

var body = Data()

let fileData = try Data(contentsOf: fileURL)
body.append("--\(boundary)\r\n".data(using: .utf8)!)
body.append("Content-Disposition: form-data; name=\"file\"; filename=\"report.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("C1234567890".data(using: .utf8)!)
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("Error: \(error)")
    }
    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::env;
use std::fs::File;
use std::io::Read;
use reqwest::blocking::Client;
use reqwest::multipart;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let token = env::var("SLACK_BOT_TOKEN")?;
    let file = File::open("report.pdf")?;

    let form = multipart::Form::new()
        .file("file", "report.pdf")?
        .text("channels", "C1234567890");

    let client = Client::new();
    let response = client
        .post("https://slack.com/api/files.upload")
        .header("Authorization", format!("Bearer {}", token))
        .multipart(form)
        .send()?;

    if !response.status().is_success() {
        return Err(format!("HTTP error! status: {}", response.status()).into());
    }

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

C# · HttpClient

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

class Program
{
    static async Task Main()
    {
        var token = Environment.GetEnvironmentVariable("SLACK_BOT_TOKEN");
        using var client = new HttpClient();
        using var form = new MultipartFormDataContent();

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

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

        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
        var response = await client.PostAsync("https://slack.com/api/files.upload", form);

        if (!response.IsSuccessStatusCode)
        {
            throw new Exception($"HTTP error! status: {response.StatusCode}");
        }

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

Translation notes

  • All implementations use the idiomatic HTTP client for each language.
  • Bearer token is read from environment variable SLACK_BOT_TOKEN.
  • File upload is handled via multipart/form-data in all cases.
  • Error handling checks HTTP status and raises/throws on failure.
  • Python implementations use requests/httpx for simplicity and readability.

Common pitfalls when porting

  • Forgetting to set Content-Type header for multipart requests in languages that don't auto-set it.
  • Not properly closing file handles or streams in languages like Go or Rust.
  • Assuming the file exists in the current working directory without validation.
  • Ignoring SSL/TLS verification in languages that allow disabling it (not shown here).
  • Using raw strings for bearer tokens instead of environment variables.

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 different deployments to use different tokens without code changes.

How do I handle large file uploads efficiently?

Use streaming/chunked uploads where supported (e.g., Python httpx, Go's io.Copy) to avoid loading the entire file into memory.

Can I use a different field name for the file upload?

Yes, but you must ensure the server (Slack API) expects the field name you provide. The default is 'file' for Slack's files.upload endpoint.