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/8a7e49bc80ea480fa961255a5b74b100 \
  -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}"
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}"
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

const fetch = require('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}`;
const headers = {
  'Authorization': `Bearer ${NOTION_TOKEN}`,
  'Notion-Version': NOTION_VERSION
};

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 NOTION_VERSION = '2022-06-28';

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

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

Go · net/http

package main

import (
	"fmt"
	"log"
	"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", DATABASE_ID)
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		log.Fatal(err)
	}

	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 {
		log.Fatal(err)
	}
	defer resp.Body.Close()

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

	// Process response body here
	_ = resp.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}";
$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);
$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);
var_dump($data);

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}")
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)
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 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)!
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 else {
        print("Invalid response")
        return
    }
    guard (200...299).contains(httpResponse.statusCode) else {
        print("HTTP error! status: \(httpResponse.statusCode)")
        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/{}", 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() {
        return Err(format!("HTTP error! status: {}", response.status()).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}";
        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)
        {
            throw new Exception($"HTTP error! status: {response.StatusCode}");
        }

        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 raises/throws on non-2xx responses
  • JSON response is parsed into a native data structure where applicable

Common pitfalls when porting

  • Forgetting to set environment variables before running the code
  • Using hardcoded secrets instead of environment variables
  • Ignoring HTTP status codes and assuming success
  • Not handling SSL/TLS properly in lower-level libraries (e.g., Go, Rust)
  • Assuming JSON response is always an object (may be array or primitive)

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 committed to version control and can be managed separately from code.

How do I set environment variables for testing?

In development, set them in your shell (e.g., export NOTION_TOKEN=your_token) or use a .env file with a library like python-dotenv.

What if the response is not JSON?

Check the Content-Type header. If it's not application/json, parse the body accordingly (e.g., as text or XML).

How do I handle pagination in the response?

The Notion API may return paginated results. Check for a 'has_more' field and use the 'next_cursor' to fetch subsequent pages.