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/pages/page_id \
  -H "Authorization: Bearer secret_1234567890abcdefghijklmnopqrstuvwxyz" \
  -H "Notion-Version: 2022-06-28"

Python · requests

import os
import requests

PAGE_ID = os.environ.get("PAGE_ID")
NOTION_TOKEN = os.environ.get("NOTION_TOKEN")
NOTION_VERSION = "2022-06-28"

if not PAGE_ID or not NOTION_TOKEN:
    raise ValueError("PAGE_ID and NOTION_TOKEN environment variables must be set")

response = requests.get(
    f"https://api.notion.com/v1/pages/{PAGE_ID}",
    headers={
        "Authorization": f"Bearer {NOTION_TOKEN}",
        "Notion-Version": NOTION_VERSION
    }
)

response.raise_for_status()
print(response.json())

Python · httpx

import os
import httpx

PAGE_ID = os.environ.get("PAGE_ID")
NOTION_TOKEN = os.environ.get("NOTION_TOKEN")
NOTION_VERSION = "2022-06-28"

if not PAGE_ID or not NOTION_TOKEN:
    raise ValueError("PAGE_ID and NOTION_TOKEN environment variables must be set")

with httpx.Client() as client:
    response = client.get(
        f"https://api.notion.com/v1/pages/{PAGE_ID}",
        headers={
            "Authorization": f"Bearer {NOTION_TOKEN}",
            "Notion-Version": NOTION_VERSION
        }
    )
    response.raise_for_status()
    print(response.json())

Node.js · fetch

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

const PAGE_ID = process.env.PAGE_ID;
const NOTION_TOKEN = process.env.NOTION_TOKEN;
const NOTION_VERSION = '2022-06-28';

if (!PAGE_ID || !NOTION_TOKEN) {
  throw new Error('PAGE_ID and NOTION_TOKEN environment variables must be set');
}

fetch(`https://api.notion.com/v1/pages/${PAGE_ID}`, {
  method: 'GET',
  headers: {
    'Authorization': `Bearer ${NOTION_TOKEN}`,
    'Notion-Version': NOTION_VERSION
  }
})
  .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 PAGE_ID = process.env.PAGE_ID;
const NOTION_TOKEN = process.env.NOTION_TOKEN;
const NOTION_VERSION = '2022-06-28';

if (!PAGE_ID || !NOTION_TOKEN) {
  throw new Error('PAGE_ID and NOTION_TOKEN environment variables must be set');
}

axios.get(`https://api.notion.com/v1/pages/${PAGE_ID}`, {
  headers: {
    'Authorization': `Bearer ${NOTION_TOKEN}`,
    'Notion-Version': NOTION_VERSION
  }
})
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    if (error.response) {
      console.error('Error:', error.response.status, error.response.data);
    } else {
      console.error('Error:', error.message);
    }
  });

Go · net/http

package main

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

func main() {
	pageID := os.Getenv("PAGE_ID")
	notionToken := os.Getenv("NOTION_TOKEN")
	notionVersion := "2022-06-28"

	if pageID == "" || notionToken == "" {
		log.Fatal("PAGE_ID and NOTION_TOKEN environment variables must be set")
	}

	req, err := http.NewRequest(
		"GET",
		fmt.Sprintf("https://api.notion.com/v1/pages/%s", pageID),
		nil,
	)
	if err != nil {
		log.Fatal(err)
	}

	req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", notionToken))
	req.Header.Set("Notion-Version", notionVersion)

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

	// In a real app, you'd decode the JSON body here
	fmt.Println("Response status:", resp.Status)
}

PHP · cURL

<?php
$pageId = getenv('PAGE_ID');
$notionToken = getenv('NOTION_TOKEN');
$notionVersion = '2022-06-28';

if (empty($pageId) || empty($notionToken)) {
    throw new Exception('PAGE_ID and NOTION_TOKEN environment variables must be set');
}

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.notion.com/v1/pages/{$pageId}");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Authorization: Bearer ' . $notionToken,
    'Notion-Version: ' . $notionVersion
]);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

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

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

Ruby · net/http

require 'net/http'
require 'json'

page_id = ENV['PAGE_ID']
notion_token = ENV['NOTION_TOKEN']
notion_version = '2022-06-28'

raise 'PAGE_ID and NOTION_TOKEN environment variables must be set' unless page_id && notion_token

uri = URI("https://api.notion.com/v1/pages/#{page_id}")
req = Net::HTTP::Get.new(uri)
req['Authorization'] = "Bearer #{notion_token}"
req['Notion-Version'] = notion_version

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}"
end

puts JSON.parse(res.body)

Swift · URLSession

import Foundation

guard let pageID = ProcessInfo.processInfo.environment["PAGE_ID"],
      let notionToken = ProcessInfo.processInfo.environment["NOTION_TOKEN"] else {
    fatalError("PAGE_ID and NOTION_TOKEN environment variables must be set")
}

let notionVersion = "2022-06-28"
let url = URL(string: "https://api.notion.com/v1/pages/" + pageID)!
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.setValue("Bearer \(notionToken)", forHTTPHeaderField: "Authorization")
request.setValue(notionVersion, 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,
          (200...299).contains(httpResponse.statusCode) else {
        print("HTTP error! status: \((response as? HTTPURLResponse)?.statusCode ?? 0)")
        return
    }
    if let data = data,
       let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
        print(json)
    }
}
task.resume()

// Keep the program running to allow async task to complete
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 page_id = env::var("PAGE_ID")?;
    let notion_token = env::var("NOTION_TOKEN")?;
    let notion_version = "2022-06-28";

    let client = reqwest::Client::new();
    let response = client
        .get(format!("https://api.notion.com/v1/pages/{}", page_id))
        .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(string[] args)
    {
        var pageId = Environment.GetEnvironmentVariable("PAGE_ID");
        var notionToken = Environment.GetEnvironmentVariable("NOTION_TOKEN");
        var notionVersion = "2022-06-28";

        if (string.IsNullOrEmpty(pageId) || string.IsNullOrEmpty(notionToken))
        {
            throw new Exception("PAGE_ID and NOTION_TOKEN environment variables must be set");
        }

        using var client = new HttpClient();
        client.DefaultRequestHeaders.Add("Authorization", $"Bearer {notionToken}");
        client.DefaultRequestHeaders.Add("Notion-Version", notionVersion);

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

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

Translation notes

  • All implementations read secrets from environment variables (PAGE_ID, NOTION_TOKEN)
  • Python httpx is async-capable but shown in sync mode for parity
  • Go uses net/http for minimal dependencies
  • Swift uses URLSession for native iOS/macOS compatibility
  • Rust uses reqwest with async/await
  • C# uses HttpClient with async/await
  • Error handling checks HTTP status codes and raises exceptions where appropriate
  • JSON parsing is implicit in most libraries (explicit in Go, Ruby, Swift)

Common pitfalls when porting

  • Forgetting to set PAGE_ID or NOTION_TOKEN environment variables
  • Using hardcoded bearer tokens instead of environment variables
  • Ignoring SSL certificate verification in Go (not shown but possible)
  • Not handling async properly in Swift (RunLoop.main.run() is a simplification)
  • Assuming JSON response structure without validation
  • Not properly closing resources (e.g., response bodies in Go)

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.

How do I handle pagination in Notion API?

Use the 'start_cursor' parameter in subsequent requests to fetch additional pages of results.

What if I need to send a POST request with a JSON body?

Add a 'json' parameter with a dictionary/object containing your body data (e.g., in Python requests: requests.post(url, json={'key': 'value'})).