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 \
  --header "Authorization: Bearer xoxb-1234567890-1234567890123-12345678901234567890123" \
  --form file=@/path/to/file.txt \
  --form channels=C1234567890 \
  --form title="Uploaded File"

Python · requests

import os
import requests

slack_token = os.environ.get("SLACK_TOKEN")
response = requests.post(
    "https://slack.com/api/files.upload",
    headers={"Authorization": f"Bearer {slack_token}"},
    files={"file": open("/path/to/file.txt", "rb")},
    data={"channels": "C1234567890", "title": "Uploaded File"}
)
response.raise_for_status()
print(response.json())

Python · httpx

import os
import httpx

slack_token = os.environ.get("SLACK_TOKEN")
with httpx.Client() as client:
    response = client.post(
        "https://slack.com/api/files.upload",
        headers={"Authorization": f"Bearer {slack_token}"},
        files={"file": open("/path/to/file.txt", "rb")},
        data={"channels": "C1234567890", "title": "Uploaded File"}
    )
    response.raise_for_status()
    print(response.json())

Node.js · fetch

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

const slackToken = env.SLACK_TOKEN;
const response = await fetch('https://slack.com/api/files.upload', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${slackToken}`
  },
  body: new FormData()
});
response.body.pipe(process.stdout);

Node.js · axios

const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');
const { env } = process;

const slackToken = env.SLACK_TOKEN;
const form = new FormData();
form.append('file', fs.createReadStream('/path/to/file.txt'));
form.append('channels', 'C1234567890');
form.append('title', 'Uploaded File');

axios.post('https://slack.com/api/files.upload', form, {
  headers: {
    ...form.getHeaders(),
    'Authorization': `Bearer ${slackToken}`
  }
})
.then(response => console.log(response.data))
.catch(error => console.error(error));

Go · net/http

package main

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

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

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

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

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

	bodyBytes, _ := io.ReadAll(resp.Body)
	fmt.Println(string(bodyBytes))
}

PHP · cURL

<?php
$slackToken = getenv('SLACK_TOKEN');

$client = new \\\CURLClient();
$client->setOption(CURLOPT_URL, 'https://slack.com/api/files.upload');
$client->setOption(CURLOPT_POST, true);
$client->setOption(CURLOPT_HTTPHEADER, [
    'Authorization: Bearer ' . $slackToken
]);

$postFields = [
    'channels' => 'C1234567890',
    'title' => 'Uploaded File'
];

$client->setOption(CURLOPT_POSTFIELDS, $postFields);
$client->setOption(CURLOPT_SAFE_UPLOAD, false);
$client->setOption(CURLOPT_RETURNTRANSFER, true);

$response = $client->execute();
echo $response;
$client->close();

Ruby · net/http

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

slack_token = ENV['SLACK_TOKEN']
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('/path/to/file.txt'), 'text/plain'),
  'channels' => 'C1234567890',
  'title' => 'Uploaded File'
)
request['Authorization'] = "Bearer #{slack_token}"

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

Swift · URLSession

import Foundation

let slackToken = ProcessInfo.processInfo.environment["SLACK_TOKEN"] ?? ""
let url = URL(string: "https://slack.com/api/files.upload")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Bearer \(slackToken)", 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: "/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)!)
body.append("Content-Disposition: form-data; name=\"channels\"\r\n\r\n".data(using: .utf8)!)
body.append("C1234567890\r\n".data(using: .utf8)!)

body.append("--\(boundary)\r\n".data(using: .utf8)!)
body.append("Content-Disposition: form-data; name=\"title\"\r\n\r\n".data(using: .utf8)!)
body.append("Uploaded File\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
    }
    if let data = data {
        print(String(data: data, encoding: .utf8) ?? "")
    }
}
task.resume()
RunLoop.main.run()

Rust · reqwest

use std::env;
use reqwest::multipart;
use tokio::fs::File;
use tokio::io::AsyncReadExt;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let slack_token = env::var("SLACK_TOKEN")?;
    let file = File::open("/path/to/file.txt").await?;
    let mut file_content = vec![];
    file.read_to_end(&mut file_content).await?;

    let form = multipart::Form::new()
        .file("file", ("/path/to/file.txt", file_content.as_slice()))?
        .text("channels", "C1234567890")
        .text("title", "Uploaded File");

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

    println!("{:?}", response.text().await?);
    Ok(())
}

C# · HttpClient

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

class Program
{
    static async Task Main()
    {
        var slackToken = Environment.GetEnvironmentVariable("SLACK_TOKEN");
        using var client = new HttpClient();
        using var form = new MultipartFormDataContent();
        using var fileStream = File.OpenRead("/path/to/file.txt");
        using var streamContent = new StreamContent(fileStream);
        using var fileContent = new MultipartFormDataContent
        {
            { streamContent, "file", "file.txt" }
        };
        form.Add(fileContent);
        form.Add(new StringContent("C1234567890"), "channels");
        form.Add(new StringContent("Uploaded File"), "title");

        client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", slackToken);
        var response = await client.PostAsync("https://slack.com/api/files.upload", form);
        response.EnsureSuccessStatusCode();
        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_TOKEN to avoid hardcoding.
  • Multipart form data is constructed correctly for file uploads.
  • Error handling is minimal but includes status code checks and response body reading.
  • Python implementations use requests and httpx libraries, which are the most common for HTTP requests.

Common pitfalls when porting

  • Forgetting to set the Content-Type header for multipart requests in languages that don't auto-set it.
  • Not properly closing file handles or streams in languages that require explicit cleanup.
  • Assuming the file path is always accessible; should handle file not found errors.
  • Not handling SSL/TLS verification in languages where it's not automatic.
  • Using raw strings for JSON bodies instead of proper object literals in languages that support structured data.

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 like API tokens. They prevent secrets from being hardcoded in source code and accidentally committed to version control.

How do I handle large file uploads efficiently?

Use streaming or chunked uploads where supported by the library. For example, in Python's requests, you can pass a file object directly to the files parameter, which streams the file.

Why is the Go implementation more verbose?

Go's standard library requires more boilerplate for multipart requests compared to higher-level libraries in other languages. This is a trade-off for not relying on external dependencies.