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

Python · requests

import os
import requests

NOTION_DATABASE_ID = os.environ["NOTION_DATABASE_ID"]
NOTION_API_KEY = os.environ["NOTION_API_KEY"]

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

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

Python · httpx

import os
import httpx

NOTION_DATABASE_ID = os.environ["NOTION_DATABASE_ID"]
NOTION_API_KEY = os.environ["NOTION_API_KEY"]

url = f"https://api.notion.com/v1/databases/{NOTION_DATABASE_ID}/query"
headers = {
    "Authorization": f"Bearer {NOTION_API_KEY}",
    "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

import fetch from 'node-fetch';

const NOTION_DATABASE_ID = process.env.NOTION_DATABASE_ID;
const NOTION_API_KEY = process.env.NOTION_API_KEY;

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

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

Node.js · axios

import axios from 'axios';

const NOTION_DATABASE_ID = process.env.NOTION_DATABASE_ID;
const NOTION_API_KEY = process.env.NOTION_API_KEY;

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

const response = await axios.get(url, { headers });
if (response.status !== 200) throw new Error(`HTTP error! status: ${response.status}`);
const data = response.data;

Go · net/http

package main

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

func main() {
	notionDatabaseID := os.Getenv("NOTION_DATABASE_ID")
	notionAPIKey := os.Getenv("NOTION_API_KEY")

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

	req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", notionAPIKey))
	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))
	}

	data, err := io.ReadAll(resp.Body)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(data))
}

PHP · cURL

<?php
$notionDatabaseId = getenv('NOTION_DATABASE_ID');
$notionApiKey = getenv('NOTION_API_KEY');

$url = "https://api.notion.com/v1/databases/{$notionDatabaseId}/query";
$headers = [
    'Authorization: Bearer ' . $notionApiKey,
    '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);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($httpCode !== 200) {
    throw new Exception("HTTP error! status: {$httpCode}");
}

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

Ruby · net/http

require 'net/http'
require 'json'

notion_database_id = ENV['NOTION_DATABASE_ID']
notion_api_key = ENV['NOTION_API_KEY']

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

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

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

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

Swift · URLSession

import Foundation

let notionDatabaseId = ProcessInfo.processInfo.environment["NOTION_DATABASE_ID"] ?? ""
let notionApiKey = ProcessInfo.processInfo.environment["NOTION_API_KEY"] ?? ""

let url = URL(string: "https://api.notion.com/v1/databases/" + notionDatabaseId + "/query")!
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.setValue("Bearer \(notionApiKey)", 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 notion_database_id = env::var("NOTION_DATABASE_ID")?;
    let notion_api_key = env::var("NOTION_API_KEY")?;

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

    if !response.status().is_success() {
        return Err(format!("HTTP error! status: {}", response.status()).into());
    }

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

C# · HttpClient

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

class Program
{
    static async Task Main()
    {
        var notionDatabaseId = Environment.GetEnvironmentVariable("NOTION_DATABASE_ID");
        var notionApiKey = Environment.GetEnvironmentVariable("NOTION_API_KEY");

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

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

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

Translation notes

  • Environment variables are used for secrets (NOTION_API_KEY, NOTION_DATABASE_ID).
  • All implementations use idiomatic HTTP clients for their respective languages.
  • Error handling checks HTTP status codes and raises exceptions/errors on failure.
  • JSON responses are parsed into native data structures where applicable.

Common pitfalls when porting

  • Forgetting to set environment variables before running the code.
  • Not handling HTTP errors properly (e.g., ignoring status codes).
  • Using hardcoded secrets in the code instead of environment variables.
  • In Go, not closing the response body can lead to resource leaks.
  • In Swift, the URLSession task must be started with `task.resume()`.

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 are a secure way to handle secrets as they are not hardcoded in the source code, reducing the risk of accidental exposure.

How do I set environment variables for these examples?

For local development, set them in your shell (e.g., `export NOTION_API_KEY=your_key` in bash). For production, use a secrets manager or deployment configuration.

Why does the Rust example use async/await?

The `reqwest` library in Rust is async by default, so the example uses async/await for non-blocking HTTP requests.