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_1234567890abcdefghijklmnopqrstuvwx" \
  -H "Content-Type: application/json" \
  -d '{"query": "{ issue(id: \"12345678-1234-1234-1234-123456789012\") { title } }"}'

Python · requests

import os
import requests

url = "https://api.linear.app/graphql"
headers = {
    "Authorization": f"Bearer {os.environ['LINEAR_API_TOKEN']}",
    "Content-Type": "application/json"
}
data = {
    "query": "{ issue(id: \"12345678-1234-1234-1234-123456789012\") { 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_TOKEN']}",
    "Content-Type": "application/json"
}
data = {
    "query": "{ issue(id: \"12345678-1234-1234-1234-123456789012\") { 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 { config } from 'dotenv';

config();

const url = 'https://api.linear.app/graphql';
const headers = {
  'Authorization': `Bearer ${process.env.LINEAR_API_TOKEN}`,
  'Content-Type': 'application/json'
};
const data = {
  query: '{ issue(id: "12345678-1234-1234-1234-123456789012") { 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 { config } from 'dotenv';

config();

const url = 'https://api.linear.app/graphql';
const headers = {
  'Authorization': `Bearer ${process.env.LINEAR_API_TOKEN}`,
  'Content-Type': 'application/json'
};
const data = {
  query: '{ issue(id: "12345678-1234-1234-1234-123456789012") { title } }'
};

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

Go · net/http

package main

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

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

func main() {
	url := "https://api.linear.app/graphql"
	token := os.Getenv("LINEAR_API_TOKEN")
	if token == "" {
		log.Fatal("LINEAR_API_TOKEN environment variable not set")
	}

	requestBody := GraphQLRequest{
		Query: "{ issue(id: \"12345678-1234-1234-1234-123456789012\") { title } }",
	}
	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 "+token)
	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 {
		log.Fatalf("HTTP error! 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';
$token = getenv('LINEAR_API_TOKEN');
if (empty($token)) {
    die('LINEAR_API_TOKEN environment variable not set');
}

$data = [
    'query' => '{ issue(id: "12345678-1234-1234-1234-123456789012") { title } }'
];

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

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

if ($result === FALSE) {
    die('Request failed');
}

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

Ruby · net/http

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

url = URI.parse('https://api.linear.app/graphql')
token = ENV.fetch('LINEAR_API_TOKEN') { raise 'LINEAR_API_TOKEN environment variable not set' }

request_body = {
  query: '{ issue(id: "12345678-1234-1234-1234-123456789012") { title } }'
}

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

request = Net::HTTP::Post.new(url.path, {
  'Authorization' => "Bearer #{token}",
  'Content-Type' => 'application/json'
})

request.body = request_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.linear.app/graphql")!
let token = ProcessInfo.processInfo.environment["LINEAR_API_TOKEN"] ?? { fatalError("LINEAR_API_TOKEN environment variable not set") }()

var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

let body: [String: Any] = [
    "query": "{ issue(id: \"12345678-1234-1234-1234-123456789012\") { title } }"
]
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 else {
        fatalError("HTTP error! status: \((response as? HTTPURLResponse)?.statusCode ?? 0)")
    }
    if let data = data, let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
        print(json)
    }
}

task.resume()
RunLoop.main.run()

Rust · reqwest

use reqwest::blocking::Client;
use std::env;

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

    let client = Client::new();
    let response = client
        .post(url)
        .header("Authorization", format!("Bearer {}", token))
        .header("Content-Type", "application/json")
        .json(&serde_json::json!({
            "query": "{ issue(id: \"12345678-1234-1234-1234-123456789012\") { title } }"
        }))
        .send()?;

    if !response.status().is_success() {
        return Err(format!("HTTP error! 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;

class Program
{
    static async Task Main()
    {
        var url = "https://api.linear.app/graphql";
        var token = Environment.GetEnvironmentVariable("LINEAR_API_TOKEN");
        if (string.IsNullOrEmpty(token))
        {
            throw new Exception("LINEAR_API_TOKEN environment variable not set");
        }

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

        var requestBody = new
        {
            query = "{ issue(id: \"12345678-1234-1234-1234-123456789012\") { title } }"
        };

        var response = await client.PostAsJsonAsync(url, requestBody);
        if (!response.IsSuccessStatusCode)
        {
            throw new Exception($"HTTP error! status: {response.StatusCode}");
        }

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

Translation notes

  • Bearer token is read from environment variable LINEAR_API_TOKEN
  • JSON body is sent as a structured object, not a raw string
  • Error handling checks HTTP status and throws on non-2xx responses
  • All implementations use idiomatic HTTP clients for their language
  • Query parameter is preserved exactly as in the original cURL

Common pitfalls when porting

  • Forgetting to set the LINEAR_API_TOKEN environment variable
  • Not handling HTTP errors properly (e.g., ignoring status codes)
  • Sending the JSON body as a raw string instead of a structured object
  • Using HTTP instead of HTTPS (Linear API requires HTTPS)
  • Not setting the Content-Type header to application/json

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 separate configuration from code, reducing the risk of accidental exposure in version control or logs. They also allow different deployments to use different credentials without code changes.

How do I handle GraphQL errors in the response?

Check the 'errors' field in the JSON response. GraphQL errors are returned in the response body even for 200 status codes. Example: if (response.errors != null) { /* handle errors */ }

Can I use a different HTTP client library?

Yes, but ensure it supports the same features: HTTPS, custom headers, JSON serialization, and error handling. Popular alternatives include Python's httpx, Node's got, and Go's fasthttp.