Qaynaq LABS · TOOLS

CURL → CODE · POST · BEARER

cURL → 10 languages

POST api.linear.app · body: json · secrets replaced with env vars.

Source cURL
curl -X GET https://api.linear.app/graphql \
  --header "Authorization: Bearer lin_api_1234567890" \
  --header "Content-Type: application/json" \
  --data '{"query":"{issues {nodes {id title}}}}"'

Python · requests

import os
import requests

url = "https://api.linear.app/graphql"
headers = {
    "Authorization": f"Bearer {os.environ['LINEAR_API_KEY']}",
    "Content-Type": "application/json"
}
body = {
    "query": "{issues {nodes {id title}}}"
}

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

Python · httpx

import os
import httpx

url = "https://api.linear.app/graphql"
headers = {
    "Authorization": f"Bearer {os.environ['LINEAR_API_KEY']}",
    "Content-Type": "application/json"
}
body = {
    "query": "{issues {nodes {id title}}}"
}

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

Node.js · fetch

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

const url = 'https://api.linear.app/graphql';
const headers = {
  'Authorization': `Bearer ${process.env.LINEAR_API_KEY}`,
  'Content-Type': 'application/json'
};
const body = {
  query: '{issues {nodes {id title}}}'
};

const response = await fetch(url, {
  method: 'POST',
  headers,
  body: JSON.stringify(body)
});

if (!response.ok) {
  throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();

Node.js · axios

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

const url = 'https://api.linear.app/graphql';
const headers = {
  'Authorization': `Bearer ${process.env.LINEAR_API_KEY}`,
  'Content-Type': 'application/json'
};
const body = {
  query: '{issues {nodes {id title}}}'
};

const response = await axios.post(url, body, { headers });
if (response.status !== 200) {
  throw new Error(`Request failed with status ${response.status}`);
}
const data = response.data;

Go · net/http

package main

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

type RequestBody struct {
	Query string `json:"query"`
}

type ResponseData struct {
	Data interface{} `json:"data"`
}

func main() {
	url := "https://api.linear.app/graphql"
	apiKey := os.Getenv("LINEAR_API_KEY")
	if apiKey == "" {
		panic("LINEAR_API_KEY environment variable not set")
	}

	reqBody := RequestBody{Query: "{issues {nodes {id title}}}"}
	bodyBytes, _ := json.Marshal(reqBody)

	req, err := http.NewRequest("POST", url, bytes.NewBuffer(bodyBytes))
	if err != nil {
		panic(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 {
		panic(err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		body, _ := io.ReadAll(resp.Body)
		panic(fmt.Sprintf("Request failed with status %d: %s", resp.StatusCode, string(body)))
	}

	var result ResponseData
	if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
		panic(err)
	}
}

PHP · cURL

<?php

$url = 'https://api.linear.app/graphql';
$apiKey = getenv('LINEAR_API_KEY');
if ($apiKey === false) {
    throw new RuntimeException('LINEAR_API_KEY environment variable not set');
}

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

$data = [
    'query' => '{issues {nodes {id title}}}'
];

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

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

if ($result === false) {
    throw new RuntimeException('Request failed');
}

$response = json_decode($result, true);
if (json_last_error() !== JSON_ERROR_NONE) {
    throw new RuntimeException('Failed to decode response');
}

Ruby · net/http

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

url = URI.parse('https://api.linear.app/graphql')
api_key = ENV.fetch('LINEAR_API_KEY')

request = Net::HTTP::Post.new(url)
request['Authorization'] = "Bearer #{api_key}"
request['Content-Type'] = 'application/json'
request.body = { query: '{issues {nodes {id title}}}' }.to_json

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

response = http.request(request)

unless response.is_a?(Net::HTTPSuccess)
  raise "Request failed with status #{response.code}: #{response.body}"
end

data = JSON.parse(response.body)

Swift · URLSession

import Foundation

let url = URL(string: "https://api.linear.app/graphql")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Bearer \(ProcessInfo.processInfo.environment["LINEAR_API_KEY"] ?? "")", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

let body: [String: Any] = [
    "query": "{issues {nodes {id title}}}"
]
request.httpBody = try? JSONSerialization.data(withJSONObject: body)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    guard let data = data, error == nil else {
        fatalError("Request failed: \(error?.localizedDescription ?? "Unknown error")")
    }
    guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
        fatalError("Request failed with status \((response as? HTTPURLResponse)?.statusCode ?? 0)")
    }
    let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any]
    print(json ?? "Invalid JSON")
}
task.resume()
RunLoop.main.run()

Rust · reqwest

use std::collections::HashMap;
use std::env;
use reqwest::blocking::Client;
use reqwest::header;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let url = "https://api.linear.app/graphql";
    let api_key = env::var("LINEAR_API_KEY")?;

    let mut headers = header::HeaderMap::new();
    headers.insert(
        "Authorization",
        header::HeaderValue::from_str(&format!("Bearer {}", api_key))?,
    );
    headers.insert(
        "Content-Type",
        header::HeaderValue::from_static("application/json"),
    );

    let body: HashMap<&str, &str> = HashMap::from([
        ("query", "{issues {nodes {id title}}}")
    ]);

    let client = Client::new();
    let response = client
        .post(url)
        .headers(headers)
        .json(&body)
        .send()?;

    if !response.status().is_success() {
        return Err(format!("Request failed with 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.linear.app/graphql";
        var apiKey = Environment.GetEnvironmentVariable("LINEAR_API_KEY");
        if (string.IsNullOrEmpty(apiKey))
        {
            throw new Exception("LINEAR_API_KEY environment variable not set");
        }

        using var client = new HttpClient();
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        var body = new { query = "{issues {nodes {id title}}}" };
        var content = new StringContent(JsonSerializer.Serialize(body), System.Text.Encoding.UTF8, "application/json");

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

        var responseBody = await response.Content.ReadAsStringAsync();
        var data = JsonSerializer.Deserialize<JsonElement>(responseBody);
        Console.WriteLine(data);
    }
}

Translation notes

  • All implementations use environment variables for secrets (LINEAR_API_KEY).
  • The cURL command uses GET but sends a JSON body, which is non-standard. Most HTTP libraries will convert this to a POST request automatically when a body is present.
  • Error handling is minimal but includes status code checks and basic error propagation.
  • JSON bodies are constructed as objects/dictionaries, not raw strings.
  • Swift uses a synchronous example for simplicity; in production, use async/await.

Common pitfalls when porting

  • Forgetting to set the Content-Type header to application/json will cause the server to reject the request.
  • Using GET with a body is unconventional; some servers may reject it outright. Always verify server expectations.
  • Not reading the response body after an error can mask the actual error message from the server.
  • In Go, forgetting to close the response body can lead to resource leaks.
  • In PHP, using file_get_contents with a stream context is simple but lacks advanced features like timeouts.

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 does the cURL command use GET with a body?

The cURL command is technically incorrect as GET requests should not have a body. Most HTTP libraries will convert this to a POST request when a body is present. Always verify the API's expected method.

How do I handle pagination or large responses?

Most libraries provide streaming or pagination helpers. For example, in Python's requests, use response.iter_content() for large files. In Go, use io.Copy() to stream the response.

Can I use a different authentication method?

Yes, replace the Authorization header with the appropriate method (e.g., Basic Auth, API key in headers, or OAuth tokens). Adjust the environment variable name accordingly.