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/db1234567890/query \
  -H "Authorization: Bearer secret_1234567890abcdefghijklmnopqrstuvwx" \
  -H "Notion-Version: 2022-06-28"

Python · requests

import os
import requests

DATABASE_ID = os.environ["DATABASE_ID"]
NOTION_TOKEN = os.environ["NOTION_TOKEN"]
NOTION_VERSION = "2022-06-28"

url = f"https://api.notion.com/v1/databases/{DATABASE_ID}/query"
headers = {
    "Authorization": f"Bearer {NOTION_TOKEN}",
    "Notion-Version": NOTION_VERSION
}

response = requests.get(url, headers=headers)
response.raise_for_status()
data = response.json()

Python · httpx

import os
import httpx

DATABASE_ID = os.environ["DATABASE_ID"]
NOTION_TOKEN = os.environ["NOTION_TOKEN"]
NOTION_VERSION = "2022-06-28"

url = f"https://api.notion.com/v1/databases/{DATABASE_ID}/query"
headers = {
    "Authorization": f"Bearer {NOTION_TOKEN}",
    "Notion-Version": NOTION_VERSION
}

with httpx.Client() as client:
    response = client.get(url, headers=headers)
    response.raise_for_status()
    data = response.json()

Node.js · fetch

import fetch from 'node-fetch';

const DATABASE_ID = process.env.DATABASE_ID;
const NOTION_TOKEN = process.env.NOTION_TOKEN;
const NOTION_VERSION = "2022-06-28";

const url = `https://api.notion.com/v1/databases/${DATABASE_ID}/query`;
const headers = {
  "Authorization": `Bearer ${NOTION_TOKEN}`,
  "Notion-Version": NOTION_VERSION
};

try {
  const response = await fetch(url, { method: 'GET', headers });
  if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
  const data = await response.json();
} catch (error) {
  console.error('Error:', error);
}

Node.js · axios

import axios from 'axios';

const DATABASE_ID = process.env.DATABASE_ID;
const NOTION_TOKEN = process.env.NOTION_TOKEN;
const NOTION_VERSION = "2022-06-28";

const url = `https://api.notion.com/v1/databases/${DATABASE_ID}/query`;
const headers = {
  "Authorization": `Bearer ${NOTION_TOKEN}`,
  "Notion-Version": NOTION_VERSION
};

try {
  const response = await axios.get(url, { headers });
  const data = response.data;
} catch (error) {
  console.error('Error:', error.message);
}

Go · net/http

package main

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

func main() {
	DATABASE_ID := os.Getenv("DATABASE_ID")
	NOTION_TOKEN := os.Getenv("NOTION_TOKEN")
	NOTION_VERSION := "2022-06-28"

	url := fmt.Sprintf("https://api.notion.com/v1/databases/%s/query", DATABASE_ID)
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		fmt.Println("Error creating request:", err)
		return
	}

	req.Header.Set("Authorization", "Bearer "+NOTION_TOKEN)
	req.Header.Set("Notion-Version", NOTION_VERSION)

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Error making request:", err)
		return
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		body, _ := io.ReadAll(resp.Body)
		fmt.Printf("Error: %s\nBody: %s\n", resp.Status, body)
		return
	}

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

PHP · cURL

<?php
$DATABASE_ID = getenv('DATABASE_ID');
$NOTION_TOKEN = getenv('NOTION_TOKEN');
$NOTION_VERSION = '2022-06-28';

$url = "https://api.notion.com/v1/databases/{$DATABASE_ID}/query";
$headers = [
    'Authorization: Bearer ' . $NOTION_TOKEN,
    'Notion-Version: ' . $NOTION_VERSION
];

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);
if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
} else {
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if ($httpCode !== 200) {
        echo "Error: HTTP $httpCode\nResponse: $response";
    } else {
        $data = json_decode($response, true);
        print_r($data);
    }
}
curl_close($ch);

Ruby · net/http

require 'net/http'
require 'json'

DATABASE_ID = ENV['DATABASE_ID']
NOTION_TOKEN = ENV['NOTION_TOKEN']
NOTION_VERSION = '2022-06-28'

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_TOKEN}"
request['Notion-Version'] = NOTION_VERSION

response = http.request(request)
if response.code != '200'
  puts "Error: #{response.code} - #{response.body}"
else
  data = JSON.parse(response.body)
  puts data
end

Swift · URLSession

import Foundation

let DATABASE_ID = ProcessInfo.processInfo.environment["DATABASE_ID"] ?? ""
let NOTION_TOKEN = ProcessInfo.processInfo.environment["NOTION_TOKEN"] ?? ""
let NOTION_VERSION = "2022-06-28"

let url = URL(string: "https://api.notion.com/v1/databases/" + DATABASE_ID + "/query")!
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.setValue("Bearer \(NOTION_TOKEN)", forHTTPHeaderField: "Authorization")
request.setValue(NOTION_VERSION, 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 == 200 else {
        print("Error: \((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;
use serde_json::Value;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let database_id = env::var("DATABASE_ID")?;
    let notion_token = env::var("NOTION_TOKEN")?;
    let notion_version = "2022-06-28";

    let url = format!("https://api.notion.com/v1/databases/{}/query", database_id);
    let client = reqwest::Client::new();
    let response = client
        .get(&url)
        .header("Authorization", format!("Bearer {}", notion_token))
        .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);
        return Err("Request failed".into());
    }

    let json: Value = response.json().await?;
    println!("{:?}", json);
    Ok(())
}

C# · HttpClient

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

class Program
{
    static async Task Main()
    {
        var DATABASE_ID = Environment.GetEnvironmentVariable("DATABASE_ID");
        var NOTION_TOKEN = Environment.GetEnvironmentVariable("NOTION_TOKEN");
        var NOTION_VERSION = "2022-06-28";

        var url = $"https://api.notion.com/v1/databases/{DATABASE_ID}/query";
        using var client = new HttpClient();
        client.DefaultRequestHeaders.Add("Authorization", $"Bearer {NOTION_TOKEN}");
        client.DefaultRequestHeaders.Add("Notion-Version", NOTION_VERSION);

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

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

Translation notes

  • All implementations read secrets from environment variables (DATABASE_ID, NOTION_TOKEN)
  • Python uses requests/httpx, Node uses fetch/axios, Go uses net/http, PHP uses cURL, Ruby uses Net::HTTP, Swift uses URLSession, Rust uses reqwest, C# uses HttpClient
  • Error handling checks HTTP status and reads response body on failure
  • URLs use environment variable for database ID to avoid hardcoding
  • Bearer token is redacted in parsed output and replaced with env var reference

Common pitfalls when porting

  • Forgetting to set DATABASE_ID and NOTION_TOKEN environment variables before running
  • Using hardcoded bearer tokens instead of environment variables
  • Ignoring HTTP status codes and assuming success
  • Not handling async/await properly in languages that require it (Swift, Rust, C#)
  • Forgetting to set the Notion-Version header which may cause API version mismatches

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

Environment variables prevent secrets from being committed to version control and allow different configurations across environments without code changes.

What if I need to pass query parameters?

Append them to the URL as standard query parameters (e.g., ?param1=value1&param2=value2) or use the appropriate method in the client library to add them.

How do I handle pagination in the Notion API?

The Notion API uses a 'start_cursor' parameter for pagination. Check the API documentation for the specific endpoint and implement cursor-based pagination accordingly.