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_1234567890" \
  -H "Content-Type: application/json" \
  -d '{"query":"mutation { issueCreate(input: { title: \"Test Issue\", teamId: \"team_id\" }) { success } }"}'

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": "mutation { issueCreate(input: { title: \"Test Issue\", teamId: \"team_id\" }) { success } }"
}

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.linear.app/graphql"
headers = {
    "Authorization": f"Bearer {os.environ['LINEAR_API_KEY']}",
    "Content-Type": "application/json"
}
data = {
    "query": "mutation { issueCreate(input: { title: \"Test Issue\", teamId: \"team_id\" }) { success } }"
}

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.linear.app/graphql';
const headers = {
  'Authorization': `Bearer ${process.env.LINEAR_API_KEY}`,
  'Content-Type': 'application/json'
};
const data = {
  query: 'mutation { issueCreate(input: { title: "Test Issue", teamId: "team_id" }) { success } }'
};

try {
  const response = await fetch(url, {
    method: 'POST',
    headers,
    body: JSON.stringify(data)
  });
  if (!response.ok) {
    throw new Error(`Request failed with status ${response.status}: ${await response.text()}`);
  }
  console.log(await response.json());
} catch (error) {
  console.error('Error:', error);
}

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 data = {
  query: 'mutation { issueCreate(input: { title: "Test Issue", teamId: "team_id" }) { success } }'
};

try {
  const response = await axios.post(url, data, { headers });
  if (response.status !== 200) {
    throw new Error(`Request failed with status ${response.status}: ${response.data}`);
  }
  console.log(response.data);
} catch (error) {
  console.error('Error:', error.message);
}

Go · net/http

package main

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

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: "mutation { issueCreate(input: { title: \"Test Issue\", teamId: \"team_id\" }) { success } }",
	}
	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.linear.app/graphql';
$apiKey = getenv('LINEAR_API_KEY');
if (empty($apiKey)) {
    die('LINEAR_API_KEY environment variable not set');
}

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

$data = [
    'query' => 'mutation { issueCreate(input: { title: "Test Issue", teamId: "team_id" }) { success } }'
];

$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 ($http_response_header[0] !== 'HTTP/1.1 200 OK') {
    die('Request failed: ' . $result);
}

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

headers = {
  'Authorization' => "Bearer #{api_key}",
  'Content-Type' => 'application/json'
}

data = {
  query: 'mutation { issueCreate(input: { title: "Test Issue", teamId: "team_id" }) { success } }'
}

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

request = Net::HTTP::Post.new(url.request_uri, headers)
request.body = data.to_json

response = http.request(request)

unless response.is_a?(Net::HTTPSuccess)
  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.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": "mutation { issueCreate(input: { title: \"Test Issue\", teamId: \"team_id\" }) { success } }"
]

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 reqwest::header;
use serde_json::json;
use std::env;

#[tokio::main]
async 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 = reqwest::Client::new();
    let response = client
        .post(url)
        .header(header::AUTHORIZATION, format!("Bearer {}", api_key))
        .header(header::CONTENT_TYPE, "application/json")
        .json(&json!({
            "query": "mutation { issueCreate(input: { title: \"Test Issue\", teamId: \"team_id\" }) { success } }"
        }))
        .send()
        .await?;

    if !response.status().is_success() {
        let status = response.status();
        let body = response.text().await?;
        return Err(format!("Request failed with status {}: {}", status, body).into());
    }

    let body = response.json::<serde_json::Value>().await?;
    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 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 requestBody = new
        {
            query = "mutation { issueCreate(input: { title: \"Test Issue\", teamId: \"team_id\" }) { success } }"
        };

        var response = await client.PostAsJsonAsync(url, requestBody);
        if (!response.IsSuccessStatusCode)
        {
            var errorContent = await response.Content.ReadAsStringAsync();
            Console.WriteLine($"Request failed with status {response.StatusCode}: {errorContent}");
            return;
        }

        var result = await response.Content.ReadFromJsonAsync<dynamic>();
        Console.WriteLine(result);
    }
}

Translation notes

  • All implementations use idiomatic HTTP clients for their respective languages.
  • Bearer tokens are read from environment variables (LINEAR_API_KEY) to avoid hardcoding secrets.
  • Error handling checks HTTP status codes and reads response bodies for diagnostics.
  • JSON bodies are constructed as objects/dictionaries, not raw strings.
  • Go and Rust examples use async/await where idiomatic.
  • PHP uses stream context for simplicity.
  • Swift uses URLSession with async/await (Swift 5.5+).

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 non-200 status codes can hide error details.
  • Hardcoding secrets in code or version control is a security risk.
  • Using raw strings for JSON bodies instead of structured objects can lead to injection or formatting issues.
  • In Go, forgetting to close the response body can lead to resource leaks.
  • In Rust, not handling async properly (e.g., missing tokio runtime) will cause runtime errors.

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 them?

Environment variables separate configuration from code, reducing the risk of secrets being exposed in version control or logs. They also allow for different configurations across environments (dev, staging, prod).

How do I handle pagination or large responses in these examples?

Most HTTP libraries support streaming or chunked responses. For example, in Python's requests, use `response.iter_content()`; in Go, use `io.Copy` with the response body; in Rust, use `response.chunk()`. For pagination, inspect the response headers or body for next-page tokens.

Can I use these examples with GraphQL subscriptions?

GraphQL subscriptions typically require WebSocket connections, which are not covered by these HTTP examples. For subscriptions, use libraries like `graphql-ws` (JavaScript) or `graphql-client` (Rust) with WebSocket support.