Qaynaq LABS · TOOLS

CURL → CODE · GET · BEARER

cURL → 10 languages

GET api.notion.com · secrets replaced with env vars.

Source cURL
curl -X GET https://api.notion.com/v1/databases/database_id/query -H "Authorization: Bearer secret_notion_api_key" -H "Notion-Version: 2022-06-28"

Python · requests

import os
import requests

NOTION_API_KEY = os.environ.get("NOTION_API_KEY")
NOTION_VERSION = os.environ.get("NOTION_VERSION", "2022-06-28")

response = requests.get(
    f"https://api.notion.com/v1/databases/{os.environ.get('DATABASE_ID')}/query",
    headers={
        "Authorization": f"Bearer {NOTION_API_KEY}",
        "Notion-Version": NOTION_VERSION
    }
)

if response.status_code >= 400:
    print(f"Error: {response.status_code} - {response.text}")
else:
    print(response.json())

Python · httpx

import os
import httpx

NOTION_API_KEY = os.environ.get("NOTION_API_KEY")
NOTION_VERSION = os.environ.get("NOTION_VERSION", "2022-06-28")

async def query_database():
    async with httpx.AsyncClient() as client:
        response = await client.get(
            f"https://api.notion.com/v1/databases/{os.environ.get('DATABASE_ID')}/query",
            headers={
                "Authorization": f"Bearer {NOTION_API_KEY}",
                "Notion-Version": NOTION_VERSION
            }
        )
        if response.status_code >= 400:
            print(f"Error: {response.status_code} - {response.text}")
        else:
            print(response.json())

# For synchronous usage:
# with httpx.Client() as client:
#     response = client.get(...)
#     ...

Node.js · fetch

const fetch = require('node-fetch');

const NOTION_API_KEY = process.env.NOTION_API_KEY;
const NOTION_VERSION = process.env.NOTION_VERSION || '2022-06-28';
const DATABASE_ID = process.env.DATABASE_ID;

fetch(`https://api.notion.com/v1/databases/${DATABASE_ID}/query`, {
    method: 'GET',
    headers: {
        'Authorization': `Bearer ${NOTION_API_KEY}`,
        'Notion-Version': NOTION_VERSION
    }
})
.then(response => {
    if (!response.ok) {
        throw new Error(`Error: ${response.status} - ${response.statusText}`);
    }
    return response.json();
})
.then(data => console.log(data))
.catch(error => console.error(error));

Node.js · axios

const axios = require('axios');

const NOTION_API_KEY = process.env.NOTION_API_KEY;
const NOTION_VERSION = process.env.NOTION_VERSION || '2022-06-28';
const DATABASE_ID = process.env.DATABASE_ID;

axios.get(`https://api.notion.com/v1/databases/${DATABASE_ID}/query`, {
    headers: {
        'Authorization': `Bearer ${NOTION_API_KEY}`,
        'Notion-Version': NOTION_VERSION
    }
})
.then(response => {
    if (response.status >= 400) {
        throw new Error(`Error: ${response.status} - ${response.statusText}`);
    }
    console.log(response.data);
})
.catch(error => console.error(error));

Go · net/http

package main

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

func main() {
	notionAPIKey := os.Getenv("NOTION_API_KEY")
	notionVersion := os.Getenv("NOTION_VERSION")
	if notionVersion == "" {
		notionVersion = "2022-06-28"
	}
	databaseID := os.Getenv("DATABASE_ID")

	client := &http.Client{}
	req, err := http.NewRequest(
		"GET",
		fmt.Sprintf("https://api.notion.com/v1/databases/%s/query", databaseID),
		nil,
	)
	if err != nil {
		log.Fatal(err)
	}

	req.Header.Set("Authorization", "Bearer "+notionAPIKey)
	req.Header.Set("Notion-Version", notionVersion)

	resp, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	if resp.StatusCode >= 400 {
		body, _ := io.ReadAll(resp.Body)
		log.Fatalf("Error: %d - %s", resp.StatusCode, string(body))
	}

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

PHP · cURL

<?php

$notionAPIKey = getenv('NOTION_API_KEY');
$notionVersion = getenv('NOTION_VERSION') ?: '2022-06-28';
$databaseID = getenv('DATABASE_ID');

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.notion.com/v1/databases/{$databaseID}/query");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Authorization: Bearer ' . $notionAPIKey,
    'Notion-Version: ' . $notionVersion
]);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($httpCode >= 400) {
    throw new Exception("Error: {$httpCode} - {$response}");
}

print_r(json_decode($response, true));

Ruby · net/http

require 'net/http'
require 'json'

notion_api_key = ENV['NOTION_API_KEY']
notion_version = ENV['NOTION_VERSION'] || '2022-06-28'
database_id = ENV['DATABASE_ID']

uri = URI.parse("https://api.notion.com/v1/databases/#{database_id}/query")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true

request = Net::HTTP::Get.new(uri.request_uri)
request['Authorization'] = "Bearer #{notion_api_key}"
request['Notion-Version'] = notion_version

response = http.request(request)

if response.code.to_i >= 400
  puts "Error: #{response.code} - #{response.body}"
else
  puts JSON.parse(response.body)
end

Swift · URLSession

import Foundation

let notionAPIKey = ProcessInfo.processInfo.environment["NOTION_API_KEY"] ?? ""
let notionVersion = ProcessInfo.processInfo.environment["NOTION_VERSION"] ?? "2022-06-28"
let databaseID = ProcessInfo.processInfo.environment["DATABASE_ID"] ?? ""

let url = URL(string: "https://api.notion.com/v1/databases/" + databaseID + "/query")!
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.setValue("Bearer " + notionAPIKey, forHTTPHeaderField: "Authorization")
request.setValue(notionVersion, forHTTPHeaderField: "Notion-Version")

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 >= 400 else {
        return
    }
    if let data = data, let responseBody = String(data: data, encoding: .utf8) {
        print("Error: \(httpResponse.statusCode) - \(responseBody)")
    }
}
task.resume()

// For synchronous usage:
// let (data, response) = try await URLSession.shared.data(for: request)
// if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode >= 400 {
//     print("Error: \(httpResponse.statusCode) - \(String(data: data, encoding: .utf8) ?? "")")
// } else {
//     print(String(data: data, encoding: .utf8) ?? "")
// }

Rust · reqwest

use std::env;
use reqwest;
use tokio;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let notion_api_key = env::var("NOTION_API_KEY")?;
    let notion_version = env::var("NOTION_VERSION").unwrap_or_else(|_| "2022-06-28".to_string());
    let database_id = env::var("DATABASE_ID")?;

    let client = reqwest::Client::new();
    let response = client
        .get(format!("https://api.notion.com/v1/databases/{}/query", database_id))
        .header("Authorization", format!("Bearer {}", notion_api_key))
        .header("Notion-Version", notion_version)
        .send()
        .await?;

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

    Ok(())
}

C# · HttpClient

using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        var notionAPIKey = Environment.GetEnvironmentVariable("NOTION_API_KEY");
        var notionVersion = Environment.GetEnvironmentVariable("NOTION_VERSION") ?? "2022-06-28";
        var databaseID = Environment.GetEnvironmentVariable("DATABASE_ID");

        using var client = new HttpClient();
        client.DefaultRequestHeaders.Add("Authorization", $"Bearer {notionAPIKey}");
        client.DefaultRequestHeaders.Add("Notion-Version", notionVersion);

        var response = await client.GetAsync($"https://api.notion.com/v1/databases/{databaseID}/query");
        if (!response.IsSuccessStatusCode)
        {
            var errorContent = await response.Content.ReadAsStringAsync();
            Console.WriteLine($"Error: {response.StatusCode} - {errorContent}");
        }
        else
        {
            var content = await response.Content.ReadAsStringAsync();
            Console.WriteLine(content);
        }
    }
}

Translation notes

  • Environment variables are used for secrets and configuration
  • Python httpx example is async; synchronous version is commented
  • Swift example uses async/await; synchronous version is commented
  • Rust example uses tokio runtime
  • PHP example uses cURL extension
  • Go example uses net/http package
  • C# example uses HttpClient

Common pitfalls when porting

  • Forgetting to set DATABASE_ID environment variable
  • Using hardcoded API keys instead of environment variables
  • Not handling HTTP errors properly
  • Ignoring SSL certificate verification in Go/Rust
  • Not setting User-Agent header (some APIs require it)
  • Assuming synchronous code works in async contexts without proper handling

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?

Environment variables separate configuration from code, reducing the risk of accidental exposure of secrets in version control.

How do I handle pagination in the Notion API?

The Notion API uses cursor-based pagination. Check the response for 'has_more' and use 'next_cursor' to fetch subsequent pages.

Why does the Swift example use async/await?

Modern Swift networking APIs are designed around async/await for better readability and performance compared to completion handlers.

Can I use this code in production without modifications?

The examples are minimal for translation purposes. Production code should include retry logic, timeouts, and more robust error handling.