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: token lin_api_1234567890" \
  -H "Content-Type: application/json" \
  -d '{"query":"mutation { issueCreate(input: { title: \"Fix bug\" }) { issue { id } } }"}'

Python · requests

import os
import requests

url = "https://api.linear.app/graphql"
headers = {
    "Authorization": f"token {os.environ['LINEAR_API_TOKEN']}",
    "Content-Type": "application/json"
}
data = {
    "query": "mutation { issueCreate(input: { title: \"Fix bug\" }) { issue { id } } }"
}

response = requests.post(url, headers=headers, json=data)
if response.status_code != 200:
    print(f"Error: {response.status_code}")
    print(response.text)

Python · httpx

import os
import httpx

url = "https://api.linear.app/graphql"
headers = {
    "Authorization": f"token {os.environ['LINEAR_API_TOKEN']}",
    "Content-Type": "application/json"
}
data = {
    "query": "mutation { issueCreate(input: { title: \"Fix bug\" }) { issue { id } } }"
}

with httpx.Client() as client:
    response = client.post(url, headers=headers, json=data)
    if response.status_code != 200:
        print(f"Error: {response.status_code}")
        print(response.text)

Node.js · fetch

import fetch from 'node-fetch';
import { config } from 'dotenv';

config();

const url = 'https://api.linear.app/graphql';
const headers = {
  'Authorization': `token ${process.env.LINEAR_API_TOKEN}`,
  'Content-Type': 'application/json'
};
const data = {
  query: 'mutation { issueCreate(input: { title: "Fix bug" }) { issue { id } } }'
};

fetch(url, {
  method: 'POST',
  headers,
  body: JSON.stringify(data)
})
  .then(res => {
    if (!res.ok) {
      console.error(`Error: ${res.status}`);
      return res.text();
    }
    return res.json();
  })
  .then(console.log)
  .catch(console.error);

Node.js · axios

import axios from 'axios';
import { config } from 'dotenv';

config();

const url = 'https://api.linear.app/graphql';
const headers = {
  'Authorization': `token ${process.env.LINEAR_API_TOKEN}`,
  'Content-Type': 'application/json'
};
const data = {
  query: 'mutation { issueCreate(input: { title: "Fix bug" }) { issue { id } } }'
};

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

Go · net/http

package main

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

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")
	}

	data := `{"query":"mutation { issueCreate(input: { title: \"Fix bug\" }) { issue { id } } }"}`
	req, err := http.NewRequest("POST", url, strings.NewReader(data))
	if err != nil {
		log.Fatal(err)
	}

	req.Header.Set("Authorization", "token "+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 {
		body, _ := io.ReadAll(resp.Body)
		log.Fatalf("Error: %d\n%s", resp.StatusCode, body)
	}

	body, _ := io.ReadAll(resp.Body)
	fmt.Println(string(body))
}

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' => 'mutation { issueCreate(input: { title: "Fix bug" }) { issue { id } } }'
];

$options = [
    'http' => [
        'header' => [
            "Authorization: token $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) {
    $error = error_get_last();
    die("Error: " . $error['message']);
}

$response = json_decode($result, true);
if (json_last_error() !== JSON_ERROR_NONE) {
    die("Error decoding response");
}

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

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

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

request.body = {
  query: 'mutation { issueCreate(input: { title: "Fix bug" }) { issue { id } } }'
}.to_json

response = http.request(request)

unless response.code == '200'
  puts "Error: #{response.code}"
  puts response.body
  exit
end

puts 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("application/json", forHTTPHeaderField: "Content-Type")

if let token = ProcessInfo.processInfo.environment["LINEAR_API_TOKEN"] {
    request.setValue("token \(token)", forHTTPHeaderField: "Authorization")
} else {
    fatalError("LINEAR_API_TOKEN environment variable not set")
}

let body: [String: Any] = [
    "query": "mutation { issueCreate(input: { title: \"Fix bug\" }) { issue { id } } }"
]

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("Error: \((response as? HTTPURLResponse)?.statusCode ?? 0)")
        if let data = data, let responseBody = String(data: data, encoding: .utf8) {
            print(responseBody)
        }
        return
    }

    if let data = data, let responseBody = String(data: data, encoding: .utf8) {
        print(responseBody)
    }
}

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

Rust · reqwest

use reqwest::blocking::Client;
use serde_json::json;
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 body = json!({
        "query": "mutation { issueCreate(input: { title: \"Fix bug\" }) { issue { id } } }"
    });

    let response = client
        .post(url)
        .header("Authorization", format!("token {}", token))
        .header("Content-Type", "application/json")
        .json(&body)
        .send()?;

    if !response.status().is_success() {
        eprintln!("Error: {}", response.status());
        eprintln!("{}", response.text()?);
    } else {
        println!("{}", response.text()?);
    }

    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 token = Environment.GetEnvironmentVariable("LINEAR_API_TOKEN");
        if (string.IsNullOrEmpty(token))
        {
            Console.WriteLine("LINEAR_API_TOKEN environment variable not set");
            return;
        }

        using var client = new HttpClient();
        var request = new HttpRequestMessage(HttpMethod.Post, url);
        request.Headers.Authorization = new AuthenticationHeaderValue("token", token);
        request.Content = new StringContent(
            JsonSerializer.Serialize(new { query = "mutation { issueCreate(input: { title: \"Fix bug\" }) { issue { id } } }" }),
            System.Text.Encoding.UTF8,
            "application/json"
        );

        var response = await client.SendAsync(request);
        if (!response.IsSuccessStatusCode)
        {
            Console.WriteLine($"Error: {response.StatusCode}");
            Console.WriteLine(await response.Content.ReadAsStringAsync());
            return;
        }

        Console.WriteLine(await response.Content.ReadAsStringAsync());
    }
}

Translation notes

  • All implementations use the idiomatic HTTP client for each language.
  • Bearer token is read from environment variable LINEAR_API_TOKEN to avoid hardcoding.
  • Error handling checks status code and prints response body on failure.
  • JSON body is constructed as a dictionary/object, not a raw string.
  • Python implementations use requests/httpx, Node uses fetch/axios, Go uses net/http, PHP uses stream context, Ruby uses Net::HTTP, Swift uses URLSession, Rust uses reqwest, C# uses HttpClient.

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 may hide error details.
  • Hardcoding the bearer token instead of using environment variables is a security risk.
  • In Go, not checking for an empty token before making the request can lead to runtime errors.
  • In Swift, not running the URLSession task will result in no request being made (RunLoop.main.run() is required in a simple script).

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 the token instead of hardcoding?

Environment variables prevent accidental exposure of secrets in version control or logs. They also allow different configurations across environments (dev, staging, prod) without code changes.

How do I handle GraphQL errors in the response?

GraphQL errors are typically returned in the response body under the 'errors' key, even if the HTTP status is 200. Check the response JSON for this key to handle GraphQL-specific errors.

Can I use a different HTTP client library in these languages?

Yes, but the provided implementations use the most idiomatic and widely adopted libraries for each language to ensure maintainability and community support.