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

Python · requests

import os
import requests

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

Python · httpx

import os
import httpx

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

Node.js · fetch

import fetch from 'node-fetch';

const response = await fetch('https://api.notion.com/v1/users', {
  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();
console.log(data);

Node.js · axios

import axios from 'axios';

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

console.log(response.data);

Go · net/http

package main

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

func main() {
	req, err := http.NewRequest("GET", "https://api.notion.com/v1/users", nil)
	if err != nil {
		panic(err)
	}

	req.Header.Set("Authorization", "Bearer "+os.Getenv("NOTION_API_KEY"))
	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: %d, body: %s", resp.StatusCode, body))
	}

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

PHP · cURL

<?php

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'https://api.notion.com/v1/users');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Authorization: Bearer ' . getenv('NOTION_API_KEY'),
    'Notion-Version: 2022-06-28'
]);

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

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

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

curl_close($ch);

Ruby · net/http

require 'net/http'
require 'json'

uri = URI('https://api.notion.com/v1/users')

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}, body: #{response.body}"
end

puts JSON.parse(response.body)

Swift · URLSession

import Foundation

let url = URL(string: "https://api.notion.com/v1/users")!
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.setValue("Bearer \(ProcessInfo.processInfo.environment["NOTION_API_KEY"] ?? "")", forHTTPHeaderField: "Authorization")
request.setValue("2022-06-28", forHTTPHeaderField: "Notion-Version")

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    guard let data = data, error == nil else {
        fatalError("Error: \(error?.localizedDescription ?? "Unknown error")")
    }

    if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode != 200 {
        fatalError("HTTP error! status: \(httpResponse.statusCode)")
    }

    if 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 reqwest::header;

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

    let client = reqwest::Client::new();
    let mut headers = header::HeaderMap::new();
    headers.insert(
        "Authorization",
        header::HeaderValue::from_str(&format!("Bearer {}", api_key))?,
    );
    headers.insert(
        "Notion-Version",
        header::HeaderValue::from_static("2022-06-28"),
    );

    let response = client
        .get("https://api.notion.com/v1/users")
        .headers(headers)
        .send()
        .await?;

    if !response.status().is_success() {
        panic!("HTTP error! status: {}", response.status());
    }

    let body = response.json::<serde_json::Value>().await?;
    println!("{:?}", body);

    Ok(())
}

C# · HttpClient

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

class Program
{
    static async Task Main()
    {
        var client = new HttpClient();
        client.DefaultRequestHeaders.Add("Authorization", $"Bearer {Environment.GetEnvironmentVariable("NOTION_API_KEY")}");
        client.DefaultRequestHeaders.Add("Notion-Version", "2022-06-28");

        var response = await client.GetAsync("https://api.notion.com/v1/users");
        response.EnsureSuccessStatusCode();

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

Translation notes

  • All implementations use environment variables for secrets (NOTION_API_KEY)
  • Error handling is minimal but includes status code checks and body reads
  • JSON bodies are handled as objects/dictionaries, not raw strings
  • Each language uses its idiomatic HTTP client library
  • Headers are preserved exactly as in the original cURL command

Common pitfalls when porting

  • Forgetting to set the NOTION_API_KEY environment variable before running
  • Not handling SSL/TLS verification (especially in Go and Ruby)
  • Assuming the response body is always JSON (may not be for errors)
  • Ignoring rate limits or pagination in the API
  • Not setting the Notion-Version header in future requests

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 instead of hardcoding?

Environment variables separate configuration from code, reducing the risk of accidental exposure in version control or logs. They also allow different configurations across environments (dev, staging, prod).

How do I handle pagination in the Notion API?

The Notion API uses cursor-based pagination. Check the response for 'has_more' and 'next_cursor' fields, then make subsequent requests with the 'start_cursor' query parameter.

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

For methods like POST or PATCH, include a JSON body by setting the 'Content-Type: application/json' header and passing a dictionary/object in the request body. Example in Python: `requests.post(url, json={'key': 'value'}, headers={...})`

How do I handle rate limits from the Notion API?

The Notion API returns rate limit information in headers like 'X-RateLimit-Limit', 'X-RateLimit-Remaining', and 'X-RateLimit-Reset'. Implement retry logic with exponential backoff when these headers indicate limits are reached.