Qaynaq LABS · TOOLS

CURL → CODE · PUT · BEARER

cURL → 10 languages

PUT api.notion.com · body: json · secrets replaced with env vars.

Source cURL
curl -X PUT https://api.notion.com/v1/databases/database_id \
  -H "Authorization: Bearer secret_1234567890" \
  -H "Notion-Version: 2022-06-28" \
  -H "Content-Type: application/json" \
  -d '{"properties":{"Name":{"title":{}}},"title":"Updated Database"}'

Python · requests

import os
import requests

url = f"https://api.notion.com/v1/databases/{os.environ['DATABASE_ID']}"
headers = {
    "Authorization": f"Bearer {os.environ['NOTION_API_KEY']}",
    "Notion-Version": "2022-06-28",
    "Content-Type": "application/json"
}
data = {
    "properties": {"Name": {"title": {}}},
    "title": "Updated Database"
}

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

Python · httpx

import os
import httpx

url = f"https://api.notion.com/v1/databases/{os.environ['DATABASE_ID']}"
headers = {
    "Authorization": f"Bearer {os.environ['NOTION_API_KEY']}",
    "Notion-Version": "2022-06-28",
    "Content-Type": "application/json"
}
data = {
    "properties": {"Name": {"title": {}}},
    "title": "Updated Database"
}

with httpx.Client() as client:
    response = client.put(url, headers=headers, json=data)
    response.raise_for_status()
    print(response.json())

Node.js · fetch

import fetch from 'node-fetch';
import { DATABASE_ID, NOTION_API_KEY } from './config.js';

const url = `https://api.notion.com/v1/databases/${DATABASE_ID}`;
const headers = {
  'Authorization': `Bearer ${NOTION_API_KEY}`,
  'Notion-Version': '2022-06-28',
  'Content-Type': 'application/json'
};
const data = {
  properties: { Name: { title: {} } },
  title: 'Updated Database'
};

try {
  const response = await fetch(url, {
    method: 'PUT',
    headers,
    body: JSON.stringify(data)
  });
  if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
  const json = await response.json();
  console.log(json);
} catch (error) {
  console.error('Error:', error);
}

Node.js · axios

import axios from 'axios';
import { DATABASE_ID, NOTION_API_KEY } from './config.js';

const url = `https://api.notion.com/v1/databases/${DATABASE_ID}`;
const headers = {
  'Authorization': `Bearer ${NOTION_API_KEY}`,
  'Notion-Version': '2022-06-28',
  'Content-Type': 'application/json'
};
const data = {
  properties: { Name: { title: {} } },
  title: 'Updated Database'
};

try {
  const response = await axios.put(url, data, { headers });
  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 (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
)

type DatabaseUpdate struct {
	Properties map[string]interface{} `json:"properties"`
	Title      string               `json:"title"`
}

func main() {
	url := fmt.Sprintf("https://api.notion.com/v1/databases/%s", os.Getenv("DATABASE_ID"))
	apiKey := os.Getenv("NOTION_API_KEY")

	data := DatabaseUpdate{
		Properties: map[string]interface{}{
			"Name": map[string]interface{}{
				"title": map[string]interface{}{},
			},
		},
		Title: "Updated Database",
	}

	jsonData, _ := json.Marshal(data)

	req, err := http.NewRequest("PUT", url, bytes.NewBuffer(jsonData))
	if err != nil {
		fmt.Println("Error creating request:", err)
		return
	}

	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Notion-Version", "2022-06-28")
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Error making request:", err)
		return
	}
	defer resp.Body.Close()

	body, _ := io.ReadAll(resp.Body)
	if resp.StatusCode != http.StatusOK {
		fmt.Printf("Error: %s\nBody: %s\n", resp.Status, body)
		return
	}

	fmt.Println(string(body))
}

PHP · cURL

<?php

$url = 'https://api.notion.com/v1/databases/' . urlencode(getenv('DATABASE_ID'));
$apiKey = getenv('NOTION_API_KEY');

$data = [
    'properties' => [
        'Name' => [
            'title' => []
        ]
    ],
    'title' => 'Updated Database'
];

$options = [
    'http' => [
        'method' => 'PUT',
        'header' => [
            'Authorization: Bearer ' . $apiKey,
            'Notion-Version: 2022-06-28',
            'Content-Type: application/json'
        ],
        'content' => json_encode($data)
    ]
];

$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);

if ($response === false) {
    throw new Exception('Request failed');
}

$httpResponse = $http_response_header;
if (strpos($httpResponse[0], 'HTTP/') === 0 && strpos($httpResponse[0], '200') === false) {
    throw new Exception('HTTP error: ' . $httpResponse[0]);
}

print_r(json_decode($response, true));

Ruby · net/http

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

url = URI.parse("https://api.notion.com/v1/databases/#{ENV['DATABASE_ID']}")
api_key = ENV['NOTION_API_KEY']

request = Net::HTTP::Put.new(url.path, {
  'Authorization' => "Bearer #{api_key}",
  'Notion-Version' => '2022-06-28',
  'Content-Type' => 'application/json'
})

request.body = {
  properties: { Name: { title: {} } },
  title: 'Updated Database'
}.to_json

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

response = http.request(request)

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

puts 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)!
var request = URLRequest(url: url)
request.httpMethod = "PUT"
request.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")
request.setValue("2022-06-28", forHTTPHeaderField: "Notion-Version")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

let body: [String: Any] = [
    "properties": ["Name": ["title": []]],
    "title": "Updated Database"
]

request.httpBody = try JSONSerialization.data(withJSONObject: body)

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, httpResponse.statusCode == 200 else {
        print("HTTP error: \((response as? HTTPURLResponse)?.statusCode ?? 0)")
        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::blocking::Client;
use serde_json::json;

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

    let url = format!("https://api.notion.com/v1/databases/{}", database_id);
    let client = Client::new();

    let body = json!({
        "properties": {"Name": {"title": {}}},
        "title": "Updated Database"
    });

    let response = client
        .put(&url)
        .header("Authorization", format!("Bearer {}", api_key))
        .header("Notion-Version", "2022-06-28")
        .header("Content-Type", "application/json")
        .json(&body)
        .send()?;

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

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

    Ok(())
}

C# · HttpClient

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        var databaseId = Environment.GetEnvironmentVariable("DATABASE_ID");
        var apiKey = Environment.GetEnvironmentVariable("NOTION_API_KEY");

        var url = $"https://api.notion.com/v1/databases/{databaseId}";
        var client = new HttpClient();

        var body = new
        {
            properties = new
            {
                Name = new { title = new object[] { } }
            },
            title = "Updated Database"
        };

        var request = new HttpRequestMessage(HttpMethod.Put, url)
        {
            Content = new StringContent(JsonSerializer.Serialize(body))
            {
                Headers = { ContentType = new MediaTypeHeaderValue("application/json") }
            }
        };

        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
        request.Headers.Add("Notion-Version", "2022-06-28");

        var response = await client.SendAsync(request);
        response.EnsureSuccessStatusCode();

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

Translation notes

  • All implementations use idiomatic HTTP clients for their language.
  • Bearer token and database ID are read from environment variables.
  • JSON bodies are constructed as objects/dicts, not raw strings.
  • Error handling checks HTTP status and reads response body.
  • Go implementation uses standard library only (no third-party HTTP clients).
  • Swift uses URLSession with async/await pattern (simplified for brevity).
  • Rust uses reqwest blocking client for simplicity (async would require more boilerplate).

Common pitfalls when porting

  • Forgetting to set Content-Type header in raw HTTP clients.
  • Not properly escaping environment variables in URLs (e.g., in Go).
  • Ignoring HTTP status codes and assuming success.
  • Hardcoding secrets in code instead of using environment variables.
  • Using string concatenation for URLs without proper encoding (e.g., in PHP).
  • Not handling JSON serialization errors in strongly-typed languages (e.g., Rust, C#).

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 separate configuration from code, reducing the risk of accidental exposure. They also allow different configurations across environments (dev, staging, prod) without code changes.

How do I handle pagination in Notion API?

The Notion API uses cursor-based pagination. Check the response for 'next_cursor' and make subsequent requests with the cursor parameter until 'has_more' is false.

Why does the Go implementation use blocking HTTP client?

The example uses the standard library's blocking client for simplicity. In production Go code, you'd typically use the async http.Client with context for better performance and cancellation support.