Qaynaq LABS · TOOLS

CURL → CODE · POST · BEARER

cURL → 10 languages

POST api.mistral.ai · body: json · secrets replaced with env vars.

Source cURL
curl -X POST https://api.mistral.ai/v1/chat/completions \
  -H "Authorization: Bearer sk-1234567890abcdefghijklmnopqrstuvwx" \
  -H "Content-Type: application/json" \
  -d '{"model":"mistral-tiny","messages":[{"role":"user","content":"Hello"}]}'

Python · requests

import os
import requests

url = "https://api.mistral.ai/v1/chat/completions"
headers = {
    "Authorization": f"Bearer {os.environ['MISTRAL_API_KEY']}",
    "Content-Type": "application/json"
}
data = {
    "model": "mistral-tiny",
    "messages": [{"role": "user", "content": "Hello"}]
}

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

Python · httpx

import os
import httpx

url = "https://api.mistral.ai/v1/chat/completions"
headers = {
    "Authorization": f"Bearer {os.environ['MISTRAL_API_KEY']}",
    "Content-Type": "application/json"
}
data = {
    "model": "mistral-tiny",
    "messages": [{"role": "user", "content": "Hello"}]
}

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

Node.js · fetch

import fetch from 'node-fetch';
import * as process from 'process';

const url = 'https://api.mistral.ai/v1/chat/completions';
const headers = {
  'Authorization': `Bearer ${process.env.MISTRAL_API_KEY}`,
  'Content-Type': 'application/json'
};
const data = {
  model: 'mistral-tiny',
  messages: [{ role: 'user', content: 'Hello' }]
};

fetch(url, {
  method: 'POST',
  headers,
  body: JSON.stringify(data)
})
  .then(res => {
    if (!res.ok) throw new Error(`HTTP error! status: ${res.status}`);
    return res.json();
  })
  .then(console.log)
  .catch(console.error);

Node.js · axios

import axios from 'axios';
import * as process from 'process';

const url = 'https://api.mistral.ai/v1/chat/completions';
const headers = {
  'Authorization': `Bearer ${process.env.MISTRAL_API_KEY}`,
  'Content-Type': 'application/json'
};
const data = {
  model: 'mistral-tiny',
  messages: [{ role: 'user', content: 'Hello' }]
};

axios.post(url, data, { headers })
  .then(res => {
    if (res.status !== 200) throw new Error(`HTTP error! status: ${res.status}`);
    console.log(res.data);
  })
  .catch(console.error);

Go · net/http

package main

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

type Message struct {
	Role    string `json:"role"`
	Content string `json:"content"`
}

type RequestBody struct {
	Model    string    `json:"model"`
	Messages []Message `json:"messages"`
}

func main() {
	url := "https://api.mistral.ai/v1/chat/completions"
	apiKey := os.Getenv("MISTRAL_API_KEY")
	if apiKey == "" {
		log.Fatal("MISTRAL_API_KEY environment variable not set")
	}

	body := RequestBody{
		Model: "mistral-tiny",
		Messages: []Message{
			{Role: "user", Content: "Hello"},
		},
	}
	jsonData, err := json.Marshal(body)
	if err != nil {
		log.Fatal(err)
	}

	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
	if err != nil {
		log.Fatal(err)
	}

	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{}
	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: %d, body: %s", resp.StatusCode, 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

$url = 'https://api.mistral.ai/v1/chat/completions';
$apiKey = getenv('MISTRAL_API_KEY');
if (empty($apiKey)) {
    die('MISTRAL_API_KEY environment variable not set');
}

$data = [
    'model' => 'mistral-tiny',
    'messages' => [
        ['role' => 'user', 'content' => 'Hello']
    ]
];

$options = [
    'http' => [
        'header' => [
            "Authorization: Bearer $apiKey",
            "Content-Type: application/json"
        ],
        'method' => 'POST',
        'content' => json_encode($data),
        'ignore_errors' => true
    ]
];

$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);

if ($http_response_header[0] !== 'HTTP/1.1 200 OK') {
    die('HTTP error! status: ' . $http_response_header[0]);
}

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

Ruby · net/http

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

url = URI.parse('https://api.mistral.ai/v1/chat/completions')
api_key = ENV.fetch('MISTRAL_API_KEY')

body = {
  model: 'mistral-tiny',
  messages: [{ role: 'user', content: 'Hello' }]
}

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

request = Net::HTTP::Post.new(url.path, {
  'Authorization' => "Bearer #{api_key}",
  'Content-Type' => 'application/json'
})
request.body = body.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://api.mistral.ai/v1/chat/completions")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Bearer \(ProcessInfo.processInfo.environment["MISTRAL_API_KEY"] ?? "")", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

let body: [String: Any] = [
    "model": "mistral-tiny",
    "messages": [
        ["role": "user", "content": "Hello"]
    ]
]

request.httpBody = try? JSONSerialization.data(withJSONObject: body)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    if let error = error {
        print("Error: \(error)")
        return
    }
    guard let httpResponse = response as? HTTPURLResponse else {
        print("Invalid response")
        return
    }
    guard (200...299).contains(httpResponse.statusCode) else {
        print("HTTP error! status: \(httpResponse.statusCode)")
        return
    }
    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 reqwest::blocking::Client;
use serde_json::json;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let url = "https://api.mistral.ai/v1/chat/completions";
    let api_key = env::var("MISTRAL_API_KEY")?;

    let client = Client::new();
    let body = json!({
        "model": "mistral-tiny",
        "messages": [{"role": "user", "content": "Hello"}]
    });

    let response = client
        .post(url)
        .header("Authorization", format!("Bearer {}", api_key))
        .header("Content-Type", "application/json")
        .json(&body)
        .send()?;

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

    let json: serde_json::Value = response.json()?;
    println!("{}", json);
    Ok(())
}

C# · HttpClient

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

class Program
{
    static async Task Main()
    {
        var url = "https://api.mistral.ai/v1/chat/completions";
        var apiKey = Environment.GetEnvironmentVariable("MISTRAL_API_KEY");
        if (string.IsNullOrEmpty(apiKey))
        {
            Console.WriteLine("MISTRAL_API_KEY environment variable not set");
            return;
        }

        var client = new HttpClient();
        var request = new HttpRequestMessage(HttpMethod.Post, url);
        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
        request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        var body = new
        {
            model = "mistral-tiny",
            messages = new[]
            {
                new { role = "user", content = "Hello" }
            }
        };

        request.Content = new StringContent(JsonSerializer.Serialize(body));
        request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

        var response = await client.SendAsync(request);
        if (!response.IsSuccessStatusCode)
        {
            Console.WriteLine($"HTTP error! status: {response.StatusCode}");
            return;
        }

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

Translation notes

  • All implementations use idiomatic HTTP clients for their respective languages.
  • Bearer token is read from environment variable MISTRAL_API_KEY to avoid hardcoding.
  • Error handling checks HTTP status and raises/logs errors if not successful.
  • JSON bodies are constructed as objects/dicts, not raw strings.
  • Go and Rust examples use blocking clients for simplicity; async variants are available.
  • PHP example uses file_get_contents with stream context for simplicity.

Common pitfalls when porting

  • Forgetting to set the Content-Type header to application/json will cause the server to reject the request.
  • Not checking the HTTP status code before parsing the response body can lead to errors if the request fails.
  • Hardcoding API keys in code instead of using environment variables is a security risk.
  • In Go, forgetting to close the response body can lead to resource leaks.
  • In Swift, the URLSession task must be started with task.resume().
  • In Rust, the reqwest blocking client is used for simplicity; async is preferred in production.

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 API key instead of hardcoding?

Environment variables keep secrets out of version control and allow different configurations across environments without code changes.

Can I use async/await in Go or Rust for better performance?

Yes, both languages support async/await. In Go, use the net/http package with goroutines or the newer net/http/httptest for async patterns. In Rust, use reqwest with async/await and tokio runtime.

How do I handle rate limits or retries in these examples?

Rate limits and retries are not shown in these minimal examples. Libraries like python-requests, httpx, axios, and Go's net/http can be extended with retry logic or rate limit handling using middleware or custom code.