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 POST https://api.linear.app/graphql \
  -H "Authorization: Bearer lin_1234567890abcdefghijklmnopqrstuv" \
  -H "Content-Type: application/json" \
  -d '{"query":"{issue(id:\"1234567890\"){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"
}
data = {
    "query": "{issue(id:\"1234567890\"){title}}"
}

response = requests.post(url, headers=headers, json=data)
response.raise_for_status()
print(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"
}
data = {
    "query": "{issue(id:\"1234567890\"){title}}"
}

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.linear.app/graphql';
const headers = {
  'Authorization': `Bearer ${process.env.LINEAR_API_KEY}`,
  'Content-Type': 'application/json'
};
const data = {
  query: '{issue(id:\"1234567890\"){title}}'
};

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(data => console.log(data))
  .catch(err => console.error(err));

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 data = {
  query: '{issue(id:\"1234567890\"){title}}'
};

axios.post(url, data, { headers })
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    if (error.response) {
      console.error('Error:', error.response.status, error.response.data);
    } else {
      console.error('Error:', error.message);
    }
  });

Go · net/http

package main

import (
	"fmt"
	"log"
	"net/http"
	"os"
	"io"
)

func main() {
	url := "https://api.linear.app/graphql"
	apiKey := os.Getenv("LINEAR_API_KEY")
	
	client := &http.Client{}
	req, err := http.NewRequest("POST", url, nil)
	if err != nil {
		log.Fatal(err)
	}
	
	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", "application/json")
	
	body := `{"query":"{issue(id:\"1234567890\"){title}}"}`
	req.Body = io.NopCloser(strings.NewReader(body))
	
	resp, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()
	
	if resp.StatusCode != http.StatusOK {
		log.Fatalf("Request failed with status: %s", resp.Status)
	}
	
	responseBody, err := io.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}
	
	fmt.Println(string(responseBody))
}

PHP · cURL

<?php

$url = 'https://api.linear.app/graphql';
$apiKey = getenv('LINEAR_API_KEY');

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

$data = [
    'query' => '{issue(id:"1234567890"){title}}'
];

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

$response = curl_exec($ch);
if (curl_errno($ch)) {
    die('Error: ' . curl_error($ch));
}

$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode !== 200) {
    die("Request failed with status: $httpCode");
}

curl_close($ch);

print_r(json_decode($response, true));
?>

Ruby · net/http

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

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

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

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

response = http.request(request)

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

puts 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": "{issue(id:\"1234567890\"){title}}"
]

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, httpResponse.statusCode == 200 else {
        print("Request failed with status: \((response as? HTTPURLResponse)?.statusCode ?? 0)")
        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.linear.app/graphql";
    let api_key = env::var("LINEAR_API_KEY")?;

    let client = Client::new();
    let response = client
        .post(url)
        .header("Authorization", format!("Bearer {}", api_key))
        .header("Content-Type", "application/json")
        .json(&json!({
            "query": "{issue(id:\"1234567890\"){title}}"
        }))
        .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.Threading.Tasks;
using System.Text.Json;

class Program
{
    static async Task Main()
    {
        var url = "https://api.linear.app/graphql";
        var apiKey = Environment.GetEnvironmentVariable("LINEAR_API_KEY");

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

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

        var response = await client.PostAsync(url, content);
        if (!response.IsSuccessStatusCode)
        {
            throw new Exception($"Request failed with 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 LINEAR_API_KEY to avoid hardcoding.
  • JSON body is constructed as a dictionary/object literal, not a raw string.
  • Error handling checks HTTP status and reads response body minimally.
  • 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 secrets from environment variables can lead to accidental exposure in version control.
  • In Go, forgetting to close the response body can lead to resource leaks.
  • In Swift, the URLSession task must be started with task.resume(), otherwise it won't execute.
  • In Rust, using reqwest::blocking requires the blocking feature and may not be suitable for async applications.

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?

Environment variables prevent secrets from being committed to version control or exposed in logs, following the principle of least privilege and security best practices.

How do I handle GraphQL errors in the response?

GraphQL errors are typically returned in the response body under the 'errors' key. Check the response JSON for this key and handle accordingly.

Can I use async/await in Python with httpx?

Yes, httpx supports async/await. Replace the synchronous code with async/await patterns for non-blocking I/O.