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

Python · requests

import os
import requests

response = requests.get(
    f"https://api.notion.com/v1/databases/{os.environ['DATABASE_ID']}/query",
    headers={
        "Authorization": f"Bearer {os.environ['NOTION_API_KEY']}",
        "Notion-Version": "2022-06-28"
    }
)
response.raise_for_status()
data = response.json()

Python · httpx

import os
import httpx

with httpx.Client() as client:
    response = client.get(
        f"https://api.notion.com/v1/databases/{os.environ['DATABASE_ID']}/query",
        headers={
            "Authorization": f"Bearer {os.environ['NOTION_API_KEY']}",
            "Notion-Version": "2022-06-28"
        }
    )
    response.raise_for_status()
    data = response.json()

Node.js · fetch

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

config();

const response = await fetch(
  `https://api.notion.com/v1/databases/${process.env.DATABASE_ID}/query`,
  {
    method: 'GET',
    headers: {
      'Authorization': `Bearer ${process.env.NOTION_API_KEY}`,
      'Notion-Version': '2022-06-28'
    }
  }
);

if (!response.ok) {
  throw new Error(`HTTP error! status: ${response.status}`);
}

const data = await response.json();

Node.js · axios

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

config();

const response = await axios.get(
  `https://api.notion.com/v1/databases/${process.env.DATABASE_ID}/query`,
  {
    headers: {
      'Authorization': `Bearer ${process.env.NOTION_API_KEY}`,
      'Notion-Version': '2022-06-28'
    }
  }
);

const data = response.data;

Go · net/http

package main

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

func main() {
	databaseID := os.Getenv("DATABASE_ID")
	apiKey := os.Getenv("NOTION_API_KEY")

	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", fmt.Sprintf("Bearer %s", apiKey))
	req.Header.Set("Notion-Version", "2022-06-28")

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

	if resp.StatusCode != http.StatusOK {
		log.Fatalf("HTTP error! status: %s", resp.Status)
	}

	// Handle response body as needed
}

PHP · cURL

<?php

$databaseId = getenv('DATABASE_ID');
$apiKey = getenv('NOTION_API_KEY');

$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 {$apiKey}",
    "Notion-Version: 2022-06-28"
]);

$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);

Ruby · net/http

require 'net/http'
require 'json'
require 'uri'

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

request = Net::HTTP::Get.new(uri)
request['Authorization'] = "Bearer #{ENV['NOTION_API_KEY']}"
request['Notion-Version'] = '2022-06-28'

response = http.request(request)

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

data = JSON.parse(response.body)

Swift · URLSession

import Foundation

let databaseId = ProcessInfo.processInfo.environment["DATABASE_ID"] ?? ""
let apiKey = ProcessInfo.processInfo.environment["NOTION_API_KEY"] ?? ""

let url = URL(string: "https://api.notion.com/v1/databases/" + databaseId + "/query")!
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.setValue("Bearer " + apiKey, 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.localizedDescription)
    }

    guard let httpResponse = response as? HTTPURLResponse,
          (200...299).contains(httpResponse.statusCode) else {
        fatalError("HTTP error! status: \(response?.description ?? "unknown")")
    }

    if let data = data,
       let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
        print(json)
    }
}

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

Rust · reqwest

use reqwest;
use std::env;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let database_id = env::var("DATABASE_ID")?;
    let api_key = env::var("NOTION_API_KEY")?;

    let client = reqwest::Client::new();
    let response = client
        .get(format!("https://api.notion.com/v1/databases/{}/query", database_id))
        .header("Authorization", format!("Bearer {}", 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 = response.json::<serde_json::Value>().await?;
    println!("{:?}", data);

    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 apiKey = Environment.GetEnvironmentVariable("NOTION_API_KEY");

        using var client = new HttpClient();
        client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
        client.DefaultRequestHeaders.Add("Notion-Version", "2022-06-28");

        var response = await client.GetAsync($"https://api.notion.com/v1/databases/{databaseId}/query");
        response.EnsureSuccessStatusCode();

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

Translation notes

  • Environment variables are used for secrets (DATABASE_ID, NOTION_API_KEY)
  • All examples preserve the original headers and method
  • Error handling is minimal but checks for HTTP success status
  • JSON parsing is included where applicable
  • Go and Swift examples are async/await where idiomatic
  • Python examples use both requests and httpx for variety

Common pitfalls when porting

  • Forgetting to set DATABASE_ID and NOTION_API_KEY in environment variables
  • Not handling HTTP errors properly (e.g., ignoring status codes)
  • Using hardcoded secrets in code instead of environment variables
  • In Go, forgetting to close the response body (defer resp.Body.Close())
  • In Swift, not running the URLSession task (e.g., missing RunLoop.main.run())
  • In Rust, missing the tokio runtime for async operations

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 is DATABASE_ID used in the URL instead of the original cURL's hardcoded ID?

The original cURL used a hardcoded database ID. In production code, this should be configurable via environment variables for flexibility and security.

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

Yes, but the examples use the most idiomatic and widely-used libraries for each language. Alternatives exist (e.g., Python's httpx, Go's net/http, etc.).

How do I handle pagination in the response?

The Notion API may return paginated results. Check the response for a 'has_more' field and use the 'next_cursor' to fetch subsequent pages. This is not shown in the examples for brevity.

Why is the Notion-Version header included?

The Notion API requires a version header to ensure compatibility. The example uses '2022-06-28', but you should use the latest stable version from Notion's documentation.