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 \
  -H "Authorization: Bearer secret_1234567890abcdefghijklmnopqrstuvwxyz" \
  -H "Notion-Version: 2022-06-28" \
  -H "Content-Type: application/json" \
  -d '{"parent":{"type":"workspace"},"title":[{"type":"title","text":{"content":"Tasks"}}],"properties":{"Name":{"type":"title"},"Status":{"type":"select","select":{"options":[{"name":"Todo","color":"red"},{"name":"Done","color":"green"}]}}}}'

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"},
    "title": [{"type": "title", "text": {"content": "Tasks"}}],
    "properties": {
        "Name": {"type": "title"},
        "Status": {
            "type": "select",
            "select": {
                "options": [
                    {"name": "Todo", "color": "red"},
                    {"name": "Done", "color": "green"}
                ]
            }
        }
    }
}

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

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"},
    "title": [{"type": "title", "text": {"content": "Tasks"}}],
    "properties": {
        "Name": {"type": "title"},
        "Status": {
            "type": "select",
            "select": {
                "options": [
                    {"name": "Todo", "color": "red"},
                    {"name": "Done", "color": "green"}
                ]
            }
        }
    }
}

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

Node.js · fetch

import fetch from 'node-fetch';
import { config } from 'dotenv';

config();

const url = 'https://api.notion.com/v1/databases';
const headers = {
  'Authorization': `Bearer ${process.env.NOTION_API_KEY}`,
  'Notion-Version': '2022-06-28',
  'Content-Type': 'application/json'
};
const data = {
  parent: { type: 'workspace' },
  title: [{ type: 'title', text: { content: 'Tasks' } }],
  properties: {
    Name: { type: 'title' },
    Status: {
      type: 'select',
      select: {
        options: [
          { name: 'Todo', color: 'red' },
          { name: 'Done', color: 'green' }
        ]
      }
    }
  }
};

fetch(url, {
  method: 'POST',
  headers,
  body: JSON.stringify(data)
})
  .then(res => {
    if (res.status >= 400) {
      return res.text().then(text => console.error(text));
    }
    return res.json();
  })
  .then(console.log)
  .catch(console.error);

Node.js · axios

import axios from 'axios';
import { config } from 'dotenv';

config();

const url = 'https://api.notion.com/v1/databases';
const headers = {
  'Authorization': `Bearer ${process.env.NOTION_API_KEY}`,
  'Notion-Version': '2022-06-28',
  'Content-Type': 'application/json'
};
const data = {
  parent: { type: 'workspace' },
  title: [{ type: 'title', text: { content: 'Tasks' } }],
  properties: {
    Name: { type: 'title' },
    Status: {
      type: 'select',
      select: {
        options: [
          { name: 'Todo', color: 'red' },
          { name: 'Done', color: 'green' }
        ]
      }
    }
  }
};

axios.post(url, data, { headers })
  .then(res => {
    if (res.status >= 400) {
      console.error(res.data);
    }
  })
  .catch(console.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"
	req, err := http.NewRequest("POST", url, nil)
	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")

	data := DatabaseRequest{
		Parent: map[string]interface{}{"type": "workspace"},
		Title: []map[string]interface{}{
			{"type": "title", "text": map[string]interface{}{"content": "Tasks"}},
		},
		Properties: map[string]interface{}{
			"Name": map[string]interface{}{"type": "title"},
			"Status": map[string]interface{}{
				"type": "select",
				"select": map[string]interface{}{
					"options": []map[string]interface{}{
						{"name": "Todo", "color": "red"},
						{"name": "Done", "color": "green"},
					},
				},
			},
		},
	}

	body, err := json.Marshal(data)
	if err != nil {
		log.Fatal(err)
	}

	req.Body = io.NopCloser(bytes.NewBuffer(body))

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

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'],
    'title' => [['type' => 'title', 'text' => ['content' => 'Tasks']]],
    'properties' => [
        'Name' => ['type' => 'title'],
        'Status' => [
            'type' => 'select',
            'select' => [
                'options' => [
                    ['name' => 'Todo', 'color' => 'red'],
                    ['name' => 'Done', 'color' => 'green']
                ]
            ]
        ]
    ]
];

$options = [
    'http' => [
        'method' => 'POST',
        'header' => $headers,
        'content' => json_encode($data),
        'ignore_errors' => true
    ]
];

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

if ($http_response_header[0] !== 'HTTP/1.1 200 OK') {
    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' },
  title: [{ type: 'title', text: { content: 'Tasks' } }],
  properties: {
    Name: { type: 'title' },
    Status: {
      type: 'select',
      select: {
        options: [
          { name: 'Todo', color: 'red' },
          { name: 'Done', color: 'green' }
        ]
      }
    }
  }
}

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

response = http.request(request)
if response.code.to_i >= 400
  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 data = [
    "parent": ["type": "workspace"],
    "title": [["type": "title", "text": ["content": "Tasks"]]],
    "properties": [
        "Name": ["type": "title"],
        "Status": [
            "type": "select",
            "select": [
                "options": [
                    ["name": "Todo", "color": "red"],
                    ["name": "Done", "color": "green"]
                ]
            ]
        ]
    ]
]

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

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

Rust · reqwest

use reqwest::blocking::Client;
use serde_json::json;
use std::env;

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

    let data = json!({
        "parent": {"type": "workspace"},
        "title": [{"type": "title", "text": {"content": "Tasks"}}],
        "properties": {
            "Name": {"type": "title"},
            "Status": {
                "type": "select",
                "select": {
                    "options": [
                        {"name": "Todo", "color": "red"},
                        {"name": "Done", "color": "green"}
                    ]
                }
            }
        }
    });

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

    if !response.status().is_success() {
        println!("{}", response.text()?);
    }

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

        var data = new
        {
            parent = new { type = "workspace" },
            title = new[] { new { type = "title", text = new { content = "Tasks" } } },
            properties = new
            {
                Name = new { type = "title" },
                Status = new
                {
                    type = "select",
                    select = new
                    {
                        options = new[]
                        {
                            new { name = "Todo", color = "red" },
                            new { name = "Done", color = "green" }
                        }
                    }
                }
            }
        };

        var content = new StringContent(JsonSerializer.Serialize(data));
        content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

        var request = new HttpRequestMessage(HttpMethod.Post, url)
        {
            Content = content
        };
        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
        request.Headers.Add("Notion-Version", "2022-06-28");

        var response = await client.SendAsync(request);
        if (!response.IsSuccessStatusCode)
        {
            var body = await response.Content.ReadAsStringAsync();
            Console.WriteLine(body);
        }
    }
}

Translation notes

  • All implementations use the official/idiomatic HTTP client for the language.
  • Bearer token is read from environment variable NOTION_API_KEY to avoid hardcoding.
  • JSON body is constructed as a native object/dict, not a raw string.
  • Error handling checks HTTP status code >= 400 and prints the response body.
  • Go uses a struct for type safety, while others use native objects.
  • PHP uses stream context for simplicity.
  • Swift uses URLSession with async/await pattern.
  • Rust uses reqwest blocking client for simplicity in example.

Common pitfalls when porting

  • Forgetting to set Content-Type header when sending JSON.
  • Not reading the API key from environment variables, leading to hardcoded secrets.
  • Ignoring HTTP status codes and assuming success.
  • Using raw strings for JSON bodies instead of native objects (breaks escaping and validation).
  • In Go, not properly closing the response body can lead to resource leaks.

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 separate configuration from code, reducing the risk of accidental exposure in version control or logs.

Can I use async/await in Python?

Yes, with httpx.AsyncClient in Python 3.7+ for async requests.

Why does Go use a struct for the body?

Go is statically typed, so using a struct ensures type safety and better IDE support.