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_1234567890abcdef" -H "Notion-Version: 2022-06-28"

Python · requests

import os
import requests

DATABASE_ID = os.environ.get("DATABASE_ID")
NOTION_TOKEN = os.environ.get("NOTION_TOKEN")

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

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

Python · httpx

import os
import httpx

DATABASE_ID = os.environ.get("DATABASE_ID")
NOTION_TOKEN = os.environ.get("NOTION_TOKEN")

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

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

Node.js · fetch

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

const DATABASE_ID = process.env.DATABASE_ID;
const NOTION_TOKEN = process.env.NOTION_TOKEN;

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

fetch(url, { method: 'GET', headers })
  .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

const axios = require('axios');

const DATABASE_ID = process.env.DATABASE_ID;
const NOTION_TOKEN = process.env.NOTION_TOKEN;

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

axios.get(url, { headers })
  .then(response => {
    if (response.status !== 200) throw new Error(`HTTP error! status: ${response.status}`);
    console.log(response.data);
  })
  .catch(err => console.error(err));

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

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

	req.Header.Set("Authorization", "Bearer "+NOTION_TOKEN)
	req.Header.Set("Notion-Version", "2022-06-28")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		body, _ := io.ReadAll(resp.Body)
		panic(fmt.Sprintf("HTTP error! status: %s, body: %s", resp.Status, body))
	}

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

PHP · cURL

<?php
$DATABASE_ID = getenv('DATABASE_ID');
$NOTION_TOKEN = getenv('NOTION_TOKEN');

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

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

$response = curl_exec($ch);
if (curl_errno($ch)) {
    die('Error: ' . curl_error($ch));
}
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($httpCode !== 200) {
    die("HTTP error! status: {$httpCode}, body: {$response}");
}

$data = json_decode($response, true);
print_r($data);

Ruby · net/http

require 'net/http'
require 'json'

DATABASE_ID = ENV['DATABASE_ID']
NOTION_TOKEN = ENV['NOTION_TOKEN']

uri = URI("https://api.notion.com/v1/databases/#{DATABASE_ID}/query")
req = Net::HTTP::Get.new(uri)
req['Authorization'] = "Bearer #{NOTION_TOKEN}"
req['Notion-Version'] = '2022-06-28'

res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
  http.request(req)
end

unless res.is_a?(Net::HTTPSuccess)
  raise "HTTP error! status: #{res.code}, body: #{res.body}"
end

data = JSON.parse(res.body)
puts data

Swift · URLSession

import Foundation

let DATABASE_ID = ProcessInfo.processInfo.environment["DATABASE_ID"] ?? ""
let NOTION_TOKEN = ProcessInfo.processInfo.environment["NOTION_TOKEN"] ?? ""

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("2022-06-28", forHTTPHeaderField: "Notion-Version")

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    if let error = error {
        fatalError("Error: \(error)")
    }
    guard let httpResponse = response as? HTTPURLResponse else {
        fatalError("Invalid response")
    }
    guard (200...299).contains(httpResponse.statusCode) else {
        fatalError("HTTP error! status: \(httpResponse.statusCode)")
    }
    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 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", "2022-06-28")
        .send()
        .await?;

    if !response.status().is_success() {
        let status = response.status();
        let body = response.text().await?;
        return Err(format!("HTTP error! status: {}, body: {}", status, body).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 databaseId = Environment.GetEnvironmentVariable("DATABASE_ID");
        var notionToken = Environment.GetEnvironmentVariable("NOTION_TOKEN");

        var url = $"https://api.notion.com/v1/databases/{databaseId}/query";
        var client = new HttpClient();
        client.DefaultRequestHeaders.Add("Authorization", $"Bearer {notionToken}");
        client.DefaultRequestHeaders.Add("Notion-Version", "2022-06-28");

        var response = await client.GetAsync(url);
        if (!response.IsSuccessStatusCode)
        {
            var content = await response.Content.ReadAsStringAsync();
            throw new Exception($"HTTP error! status: {response.StatusCode}, body: {content}");
        }

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

Translation notes

  • All implementations read secrets from environment variables (DATABASE_ID, NOTION_TOKEN).
  • Python uses requests/httpx, Node.js 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.
  • JSON responses are parsed into native data structures where applicable.

Common pitfalls when porting

  • Forgetting to set DATABASE_ID and NOTION_TOKEN environment variables will cause runtime errors.
  • In Go, ensure the HTTP client is properly closed or reused to avoid resource leaks.
  • In Swift, the URLSession task must be started with task.resume() and the run loop must be kept alive.
  • In Rust, async/await requires a runtime like tokio; ensure the Cargo.toml includes reqwest with the 'json' feature.
  • In PHP, curl_setopt must include CURLOPT_RETURNTRANSFER to capture the response body.

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 are a secure way to manage secrets, avoiding exposure in source code or version control. They can be injected at runtime in CI/CD pipelines or containerized environments.

How do I handle pagination in the Notion API response?

The Notion API returns a 'has_more' flag and a 'next_cursor' in the response. Use these to make subsequent requests with the 'start_cursor' query parameter until 'has_more' is false.