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_api_1234567890abcdefghijklmnopqrstuvwx" \
  -H "Content-Type: application/json" \
  -d '{"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()
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"
}
body = {"query": "{issues {nodes {id title}}}"}

with httpx.Client() as client:
    response = client.post(url, headers=headers, json=body)
    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_KEY}`,
  'Content-Type': 'application/json'
};
const body = { query: '{issues {nodes {id title}}}' };

fetch(url, {
  method: 'POST',
  headers,
  body: JSON.stringify(body)
})
  .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_KEY}`,
  'Content-Type': 'application/json'
};
const body = { query: '{issues {nodes {id title}}}' };

axios.post(url, body, { headers })
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });

Go · net/http

package main

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

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

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

	requestBody := GraphQLRequest{Query: "{issues {nodes {id title}}}"}
	bodyBytes, err := json.Marshal(requestBody)
	if err != nil {
		log.Fatal(err)
	}

	req, err := http.NewRequest("POST", url, bytes.NewBuffer(bodyBytes))
	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 {
		log.Fatalf("Request failed with status: %s", resp.Status)
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(string(body))
}

PHP · cURL

<?php

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

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

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

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

$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')
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}"
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": "{issues {nodes {id 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 body = json!({ "query": "{issues {nodes {id title}}}" });

    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!("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.Threading.Tasks;
using System.Text.Json;

class Program
{
    static async Task Main(string[] args)
    {
        var url = "https://api.linear.app/graphql";
        var apiKey = Environment.GetEnvironmentVariable("LINEAR_API_KEY");
        if (string.IsNullOrEmpty(apiKey))
        {
            Console.WriteLine("LINEAR_API_KEY environment variable not set");
            return;
        }

        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);
        if (!response.IsSuccessStatusCode)
        {
            Console.WriteLine($"Request failed with status: {response.StatusCode}");
            return;
        }

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

Translation notes

  • All implementations use environment variables for secrets (LINEAR_API_KEY)
  • JSON bodies are constructed as objects/dictionaries, not raw strings
  • Error handling includes status code checks and basic error reporting
  • Each language uses its idiomatic HTTP client library
  • Bearer token is redacted in the parsed schema

Common pitfalls when porting

  • Forgetting to set the LINEAR_API_KEY environment variable
  • Not handling SSL/TLS verification (especially in Go and Ruby)
  • Ignoring HTTP status codes in error handling
  • Using raw strings for JSON bodies instead of proper serialization
  • Not setting Content-Type header explicitly in some languages

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 are more secure as they don't appear in source code or version control. They can also be easily changed without modifying the code.

How do I handle pagination in the GraphQL response?

The response will include a 'pageInfo' field with 'hasNextPage' and 'endCursor' fields. Use these to construct subsequent requests with the 'after' parameter.

What if I need to send variables with the GraphQL query?

Add a 'variables' field to the request body: { "query": "...", "variables": { "key": "value" } }.