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 mapi-12345678-1234-1234-1234-1234567890ab" -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)
if response.status_code != 200:
    raise Exception(f"Request failed with status {response.status_code}: {response.text}")
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)
    if response.status_code != 200:
        raise Exception(f"Request failed with status {response.status_code}: {response.text}")
    print(response.json())

Node.js · fetch

import fetch from 'node-fetch';
import { config } from 'dotenv';

config();

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(async response => {
    if (!response.ok) {
      throw new Error(`Request failed with status ${response.status}: ${await response.text()}`);
    }
    return response.json();
  })
  .then(console.log)
  .catch(console.error);

Node.js · axios

import axios from 'axios';
import { config } from 'dotenv';

config();

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(response => {
    if (response.status !== 200) {
      throw new Error(`Request failed with status ${response.status}: ${response.statusText}`);
    }
    console.log(response.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() {
	apiKey := os.Getenv("MISTRAL_API_KEY")
	if apiKey == "" {
		log.Fatal("MISTRAL_API_KEY environment variable not set")
	}

	url := "https://api.mistral.ai/v1/chat/completions"
	requestBody := RequestBody{
		Model: "mistral-tiny",
		Messages: []Message{
			{Role: "user", Content: "Hello!"},
		},
	}

	body, err := json.Marshal(requestBody)
	if err != nil {
		log.Fatal(err)
	}

	req, err := http.NewRequest("POST", url, bytes.NewBuffer(body))
	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("Request failed with status %d: %s", resp.StatusCode, string(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');
}

$headers = [
    'Authorization: Bearer ' . $apiKey,
    'Content-Type: application/json'
];

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

$options = [
    'http' => [
        'header' => $headers,
        'method' => 'POST',
        'content' => json_encode($data),
        'ignore_errors' => true
    ]
];

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

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

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

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')

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 = {
  model: 'mistral-tiny',
  messages: [{ role: 'user', content: 'Hello!' }]
}.to_json

response = http.request(request)

unless response.code == '200'
  raise "Request failed with status #{response.code}: #{response.body}"
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"

let apiKey = ProcessInfo.processInfo.environment["MISTRAL_API_KEY"] ?? ""
if apiKey.isEmpty {
    fatalError("MISTRAL_API_KEY environment variable not set")
}

request.setValue("Bearer \(apiKey)", 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 {
        fatalError("Request failed: \(error)")
    }

    guard let httpResponse = response as? HTTPURLResponse,
          httpResponse.statusCode == 200,
          let data = data else {
        fatalError("Request failed with status \((response as? HTTPURLResponse)?.statusCode ?? 0)")
    }

    do {
        if let json = try JSONSerialization.jsonObject(with: data) as? [String: Any] {
            print(json)
        }
    } catch {
        fatalError("Failed to parse response: \(error)")
    }
}

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 api_key = env::var("MISTRAL_API_KEY")?;
    let url = "https://api.mistral.ai/v1/chat/completions";

    let client = Client::new();
    let response = client
        .post(url)
        .header("Authorization", format!("Bearer {}", api_key))
        .header("Content-Type", "application/json")
        .json(&json!({
            "model": "mistral-tiny",
            "messages": [{"role": "user", "content": "Hello!"}]
        }))
        .send()?;

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

    let body = response.text()?;
    println!("{}", body);
    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 apiKey = Environment.GetEnvironmentVariable("MISTRAL_API_KEY");
        if (string.IsNullOrEmpty(apiKey))
        {
            throw new Exception("MISTRAL_API_KEY environment variable not set");
        }

        var url = "https://api.mistral.ai/v1/chat/completions";
        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)
        {
            throw new Exception($"Request failed with status {response.StatusCode}: {await response.Content.ReadAsStringAsync()}");
        }

        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 MISTRAL_API_KEY to avoid hardcoding.
  • Error handling checks HTTP status and reads response body on failure.
  • JSON bodies are constructed as objects/dicts, not raw strings.
  • Python implementations use both requests and httpx for completeness.

Common pitfalls when porting

  • Forgetting to set the Content-Type header to application/json will cause the server to reject the request.
  • Not reading the response body on failure can hide error details from the server.
  • Hardcoding secrets in code is a security risk; always use environment variables.
  • In Go, forgetting to close the response body can lead to resource leaks.
  • In Swift, the URLSession task runs asynchronously; ensure the RunLoop is active to complete the request.
  • In Rust, using reqwest::blocking requires a blocking runtime; async alternatives exist but are more complex.

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

Hardcoding secrets in source code is a security risk. Environment variables allow secrets to be injected at runtime without exposing them in version control or logs.

How do I handle pagination or large responses?

Most HTTP clients provide streaming or chunked response handling. For example, in Python's requests, use response.iter_content() for large downloads.

Can I use a proxy with these clients?

Yes, most clients support proxy configuration. For example, in Python requests: requests.post(url, proxies={'http': 'http://proxy:port', 'https': 'http://proxy:port'}, ...)