Qaynaq LABS · TOOLS

CURL → CODE · POST · BEARER

cURL → 10 languages

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

Source cURL
curl -X POST https://api.notion.com/v1/databases \
  --header "Authorization: Bearer secret_1234567890" \
  --header "Notion-Version: 2022-06-28" \
  --header "Content-Type: application/json" \
  --data '{"parent":{"type":"workspace_id","workspace_id":"12345678-90ab-cdef-1234-567890abcdef"},"title":[{"type":"title","title":[{"type":"text","text":{"content":"New Database"}}]}],"properties":{"Name":{"title":{}}}}'

Python · requests

import os
import requests

url = "https://api.notion.com/v1/databases"
headers = {
    "Authorization": f"Bearer {os.environ['NOTION_API_KEY']}",
    "Notion-Version": "2022-06-28",
    "Content-Type": "application/json"
}
data = {
    "parent": {"type": "workspace_id", "workspace_id": "12345678-90ab-cdef-1234-567890abcdef"},
    "title": [{"type": "title", "title": [{"type": "text", "text": {"content": "New Database"}}]}],
    "properties": {"Name": {"title": {}}}
}

response = requests.post(url, headers=headers, json=data)
if response.status_code >= 400:
    print(response.text)
else:
    print(response.json())

Python · httpx

import os
import httpx

url = "https://api.notion.com/v1/databases"
headers = {
    "Authorization": f"Bearer {os.environ['NOTION_API_KEY']}",
    "Notion-Version": "2022-06-28",
    "Content-Type": "application/json"
}
data = {
    "parent": {"type": "workspace_id", "workspace_id": "12345678-90ab-cdef-1234-567890abcdef"},
    "title": [{"type": "title", "title": [{"type": "text", "text": {"content": "New Database"}}]}],
    "properties": {"Name": {"title": {}}}
}

with httpx.Client() as client:
    response = client.post(url, headers=headers, json=data)
    if response.status_code >= 400:
        print(response.text)
    else:
        print(response.json())

Node.js · fetch

import fetch from 'node-fetch';
import { env } from 'process';

const url = 'https://api.notion.com/v1/databases';
const headers = {
  'Authorization': `Bearer ${env.NOTION_API_KEY}`,
  'Notion-Version': '2022-06-28',
  'Content-Type': 'application/json'
};
const data = {
  parent: { type: 'workspace_id', workspace_id: '12345678-90ab-cdef-1234-567890abcdef' },
  title: [{ type: 'title', title: [{ type: 'text', text: { content: 'New Database' } }] }],
  properties: { Name: { title: {} } }
};

try {
  const response = await fetch(url, {
    method: 'POST',
    headers,
    body: JSON.stringify(data)
  });
  if (!response.ok) {
    console.log(await response.text());
  } else {
    console.log(await response.json());
  }
} catch (error) {
  console.error(error);
}

Node.js · axios

import axios from 'axios';
import { env } from 'process';

const url = 'https://api.notion.com/v1/databases';
const headers = {
  'Authorization': `Bearer ${env.NOTION_API_KEY}`,
  'Notion-Version': '2022-06-28',
  'Content-Type': 'application/json'
};
const data = {
  parent: { type: 'workspace_id', workspace_id: '12345678-90ab-cdef-1234-567890abcdef' },
  title: [{ type: 'title', title: [{ type: 'text', text: { content: 'New Database' } }] }],
  properties: { Name: { title: {} } }
};

try {
  const response = await axios.post(url, data, { headers });
  if (response.status >= 400) {
    console.log(response.data);
  } else {
    console.log(response.data);
  }
} catch (error) {
  console.error(error);
}

Go · net/http

package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
)

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

func main() {
	url := "https://api.notion.com/v1/databases"
	reqBody := DatabaseRequest{
		Parent: map[string]interface{}{
			"type":          "workspace_id",
			"workspace_id":  "12345678-90ab-cdef-1234-567890abcdef",
		},
		Title: []map[string]interface{}{
			{
				"type": "title",
				"title": []map[string]interface{}{
					{
						"type": "text",
						"text": map[string]interface{}{
							"content": "New Database",
						},
					},
				},
			},
		},
		Properties: map[string]interface{}{
			"Name": map[string]interface{}{
				"title": map[string]interface{}{},
			},
		},
	}
	body, _ := json.Marshal(reqBody)

	req, err := http.NewRequest("POST", url, bytes.NewBuffer(body))
	if err != nil {
		log.Fatal(err)
	}

	req.Header.Set("Authorization", "Bearer "+os.Getenv("NOTION_API_KEY"))
	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 {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	if resp.StatusCode >= 400 {
		body, _ := io.ReadAll(resp.Body)
		fmt.Println(string(body))
	} else {
		body, _ := io.ReadAll(resp.Body)
		fmt.Println(string(body))
	}
}

PHP · cURL

<?php

$url = 'https://api.notion.com/v1/databases';
$headers = [
    'Authorization: Bearer ' . getenv('NOTION_API_KEY'),
    'Notion-Version: 2022-06-28',
    'Content-Type: application/json'
];
$data = [
    'parent' => [
        'type' => 'workspace_id',
        'workspace_id' => '12345678-90ab-cdef-1234-567890abcdef'
    ],
    'title' => [[
        'type' => 'title',
        'title' => [[
            'type' => 'text',
            'text' => [
                'content' => 'New Database'
            ]
        ]]
    ]],
    'properties' => [
        'Name' => [
            'title' => []
        ]
    ]
];

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

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

if ($httpCode >= 400) {
    echo $response;
} else {
    echo $response;
}

Ruby · net/http

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

url = URI.parse('https://api.notion.com/v1/databases')
headers = {
  'Authorization' => "Bearer #{ENV['NOTION_API_KEY']}",
  'Notion-Version' => '2022-06-28',
  'Content-Type' => 'application/json'
}
data = {
  parent: {
    type: 'workspace_id',
    workspace_id: '12345678-90ab-cdef-1234-567890abcdef'
  },
  title: [{
    type: 'title',
    title: [{
      type: 'text',
      text: {
        content: 'New Database'
      }
    }]
  }],
  properties: {
    Name: {
      title: {}
    }
  }
}

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Post.new(url.request_uri, headers)
request.body = data.to_json

response = http.request(request)
if response.code.to_i >= 400
  puts response.body
else
  puts response.body
end

Swift · URLSession

import Foundation

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

let body: [String: Any] = [
    "parent": [
        "type": "workspace_id",
        "workspace_id": "12345678-90ab-cdef-1234-567890abcdef"
    ],
    "title": [[
        "type": "title",
        "title": [[
            "type": "text",
            "text": [
                "content": "New Database"
            ]
        ]]
    ]],
    "properties": [
        "Name": [
            "title": [:]
        ]
    ]
]

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

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    if let error = error {
        print(error)
        return
    }
    guard let httpResponse = response as? HTTPURLResponse else {
        print("Invalid response")
        return
    }
    if httpResponse.statusCode >= 400 {
        if let data = data, let responseBody = String(data: data, encoding: .utf8) {
            print(responseBody)
        }
    } else {
        if let data = data, let responseBody = String(data: data, encoding: .utf8) {
            print(responseBody)
        }
    }
}
task.resume()
RunLoop.main.run()

Rust · reqwest

use reqwest::header;
use serde_json::json;
use std::env;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let url = "https://api.notion.com/v1/databases";
    let api_key = env::var("NOTION_API_KEY")?;

    let client = reqwest::Client::new();
    let response = client
        .post(url)
        .header(header::AUTHORIZATION, format!("Bearer {}", api_key))
        .header("Notion-Version", "2022-06-28")
        .header(header::CONTENT_TYPE, "application/json")
        .json(&json!({
            "parent": {
                "type": "workspace_id",
                "workspace_id": "12345678-90ab-cdef-1234-567890abcdef"
            },
            "title": [{
                "type": "title",
                "title": [{
                    "type": "text",
                    "text": {
                        "content": "New Database"
                    }
                }]
            }],
            "properties": {
                "Name": {
                    "title": {}
                }
            }
        }))
        .send()
        .await?;

    if response.status().as_u16() >= 400 {
        println!("{}", response.text().await?);
    } else {
        println!("{}", response.text().await?);
    }

    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 url = "https://api.notion.com/v1/databases";
        var apiKey = Environment.GetEnvironmentVariable("NOTION_API_KEY");

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

        var body = new
        {
            parent = new
            {
                type = "workspace_id",
                workspace_id = "12345678-90ab-cdef-1234-567890abcdef"
            },
            title = new[]
            {
                new
                {
                    type = "title",
                    title = new[]
                    {
                        new
                        {
                            type = "text",
                            text = new { content = "New Database" }
                        }
                    }
                }
            },
            properties = new
            {
                Name = new { title = new { } }
            }
        };

        var response = await client.PostAsJsonAsync(url, body);
        if (!response.IsSuccessStatusCode)
        {
            Console.WriteLine(await response.Content.ReadAsStringAsync());
        }
        else
        {
            Console.WriteLine(await response.Content.ReadAsStringAsync());
        }
    }
}

Translation notes

  • All implementations use idiomatic HTTP clients for their respective languages.
  • Bearer token is read from environment variable NOTION_API_KEY to avoid hardcoding.
  • JSON body is constructed as a native object/struct, not as a raw string.
  • Error handling checks HTTP status code and prints response body if >= 400.
  • Headers are set explicitly for clarity and fidelity to the original cURL.

Common pitfalls when porting

  • Forgetting to set the Notion-Version header may cause API version mismatches.
  • Not reading the API key from an environment variable risks secret leakage.
  • Incorrect JSON structure in the request body will result in API errors.
  • Assuming the API key is always available in the environment without fallback handling.
  • Ignoring SSL/TLS verification in Go or other languages may lead to security issues.

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 secret exposure in version control or logs. They also allow easy rotation of secrets without code changes.

How do I handle pagination or rate limits in these clients?

These examples focus on a single request. For pagination, check response headers like 'Notion-Cursor' or 'Has-More'. For rate limits, inspect 'Retry-After' headers and implement exponential backoff.