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/blocks/block_id/children \
  -H "Authorization: Bearer secret_1234567890abcdefghijklmnopqrstuvwx" \
  -H "Notion-Version: 2022-06-28" \
  -H "Content-Type: application/json" \
  -d '{"children": [{"object": "block", "type": "paragraph", "paragraph": {"rich_text": [{"type": "text", "text": {"content": "Updated paragraph text"}}]}}]}'

Python · requests

import os
import requests

block_id = "block_id"
url = f"https://api.notion.com/v1/blocks/{block_id}/children"
headers = {
    "Authorization": f"Bearer {os.environ['NOTION_API_KEY']}",
    "Notion-Version": "2022-06-28",
    "Content-Type": "application/json"
}
data = {
    "children": [{
        "object": "block",
        "type": "paragraph",
        "paragraph": {
            "rich_text": [{
                "type": "text",
                "text": {"content": "Updated paragraph text"}
            }]
        }
    }]
}

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

Python · httpx

import os
import httpx

block_id = "block_id"
url = f"https://api.notion.com/v1/blocks/{block_id}/children"
headers = {
    "Authorization": f"Bearer {os.environ['NOTION_API_KEY']}",
    "Notion-Version": "2022-06-28",
    "Content-Type": "application/json"
}
data = {
    "children": [{
        "object": "block",
        "type": "paragraph",
        "paragraph": {
            "rich_text": [{
                "type": "text",
                "text": {"content": "Updated paragraph text"}
            }]
        }
    }]
}

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

Node.js · fetch

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

const blockId = 'block_id';
const url = `https://api.notion.com/v1/blocks/${blockId}/children`;
const headers = {
  'Authorization': `Bearer ${process.env.NOTION_API_KEY}`,
  'Notion-Version': '2022-06-28',
  'Content-Type': 'application/json'
};
const data = {
  children: [{
    object: 'block',
    type: 'paragraph',
    paragraph: {
      rich_text: [{
        type: 'text',
        text: { content: 'Updated paragraph text' }
      }]
    }
  }]
};

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

Node.js · axios

const axios = require('axios');

const blockId = 'block_id';
const url = `https://api.notion.com/v1/blocks/${blockId}/children`;
const headers = {
  'Authorization': `Bearer ${process.env.NOTION_API_KEY}`,
  'Notion-Version': '2022-06-28',
  'Content-Type': 'application/json'
};
const data = {
  children: [{
    object: 'block',
    type: 'paragraph',
    paragraph: {
      rich_text: [{
        type: 'text',
        text: { content: 'Updated paragraph text' }
      }]
    }
  }]
};

axios.put(url, data, { headers })
  .then(res => {
    if (res.status >= 400) {
      console.error(res.data);
    }
  })
  .catch(err => console.error(err));

Go · net/http

package main

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

func main() {
	blockID := "block_id"
	url := fmt.Sprintf("https://api.notion.com/v1/blocks/%s/children", blockID)
	
	requestBody := map[string]interface{}{
		"children": []map[string]interface{}{
			{
				"object":  "block",
				"type":    "paragraph",
				"paragraph": map[string]interface{}{
					"rich_text": []map[string]interface{}{
						{
							"type": "text",
							"text": map[string]interface{}{
								"content": "Updated paragraph text",
							},
						},
					},
				},
			},
		},
	}
	
	body, _ := json.Marshal(requestBody)
	
	req, err := http.NewRequest("PUT", url, bytes.NewBuffer(body))
	if err != nil {
		fmt.Println(err)
		return
	}
	
	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 {
		fmt.Println(err)
		return
	}
	defer resp.Body.Close()
	
	if resp.StatusCode >= 400 {
		body, _ := io.ReadAll(resp.Body)
		fmt.Println(string(body))
	}
}

PHP · cURL

<?php

$blockId = 'block_id';
$url = "https://api.notion.com/v1/blocks/$blockId/children";

$headers = [
    'Authorization: Bearer ' . getenv('NOTION_API_KEY'),
    'Notion-Version: 2022-06-28',
    'Content-Type: application/json'
];

$data = [
    'children' => [[
        'object' => 'block',
        'type' => 'paragraph',
        'paragraph' => [
            'rich_text' => [[
                'type' => 'text',
                'text' => ['content' => 'Updated paragraph text']
            ]]
        ]
    ]]
];

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

$response = curl_exec($ch);
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) >= 400) {
    echo $response;
}
curl_close($ch);

Ruby · net/http

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

block_id = 'block_id'
url = URI.parse("https://api.notion.com/v1/blocks/#{block_id}/children")

headers = {
  'Authorization' => "Bearer #{ENV['NOTION_API_KEY']}",
  'Notion-Version' => '2022-06-28',
  'Content-Type' => 'application/json'
}

data = {
  children: [{
    object: 'block',
    type: 'paragraph',
    paragraph: {
      rich_text: [{
        type: 'text',
        text: { content: 'Updated paragraph text' }
      }]
    }
  }]
}

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Put.new(url.request_uri, 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 blockId = "block_id"
let url = URL(string: "https://api.notion.com/v1/blocks/" + blockId + "/children")!

var request = URLRequest(url: url)
request.httpMethod = "PUT"
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] = [
    "children": [
        [
            "object": "block",
            "type": "paragraph",
            "paragraph": [
                "rich_text": [
                    [
                        "type": "text",
                        "text": ["content": "Updated paragraph text"]
                    ]
                ]
            ]
        ]
    ]
]

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
    }
    if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode >= 400, let data = data {
        print(String(data: data, encoding: .utf8) ?? "")
    }
}
task.resume()
RunLoop.main.run()

Rust · reqwest

use reqwest::blocking::Client;
use std::collections::HashMap;
use std::env;

fn main() {
    let block_id = "block_id";
    let url = format!("https://api.notion.com/v1/blocks/{}/children", block_id);
    
    let client = Client::new();
    let mut headers = reqwest::header::HeaderMap::new();
    headers.insert(
        "Authorization",
        format!("Bearer {}", env::var("NOTION_API_KEY").unwrap()).parse().unwrap(),
    );
    headers.insert("Notion-Version", "2022-06-28".parse().unwrap());
    headers.insert("Content-Type", "application/json".parse().unwrap());
    
    let body: HashMap<&str, Vec<HashMap<&str, serde_json::Value>>> = HashMap::from([(
        "children", vec![HashMap::from([
            ("object", serde_json::json!("block")),
            ("type", serde_json::json!("paragraph")),
            ("paragraph", serde_json::json!({
                "rich_text": vec![HashMap::from([
                    ("type", serde_json::json!("text")),
                    ("text", serde_json::json!({"content": "Updated paragraph text"}))
                ])]
            }))
        ])]
    )]);
    
    let response = client.put(&url)
        .headers(headers)
        .json(&body)
        .send()
        .unwrap();
    
    if response.status().as_u16() >= 400 {
        println!("{}", response.text().unwrap());
    }
}

C# · HttpClient

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

class Program
{
    static async Task Main()
    {
        var blockId = "block_id";
        var url = $"https://api.notion.com/v1/blocks/{blockId}/children";
        
        using var client = new HttpClient();
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
            "Bearer", 
            Environment.GetEnvironmentVariable("NOTION_API_KEY")
        );
        client.DefaultRequestHeaders.Add("Notion-Version", "2022-06-28");
        
        var body = new {
            children = new[] {
                new {
                    @object = "block",
                    type = "paragraph",
                    paragraph = new {
                        rich_text = new[] {
                            new {
                                type = "text",
                                text = new { content = "Updated paragraph text" }
                            }
                        }
                    }
                }
            }
        };
        
        var response = await client.PutAsync(
            url,
            new StringContent(JsonSerializer.Serialize(body), System.Text.Encoding.UTF8, "application/json")
        );
        
        if (!response.IsSuccessStatusCode)
        {
            var content = await response.Content.ReadAsStringAsync();
            Console.WriteLine(content);
        }
    }
}

Translation notes

  • All implementations use the idiomatic HTTP client for each language.
  • Bearer token is read from environment variable NOTION_API_KEY.
  • JSON body is constructed as a native object/struct/dict.
  • Error handling checks HTTP status code >= 400 and prints the response body.
  • URL path parameter {block_id} is left as a placeholder for runtime substitution.

Common pitfalls when porting

  • Forgetting to set Content-Type header when sending JSON bodies.
  • Not handling HTTP errors properly (e.g., ignoring status codes).
  • Hardcoding secrets instead of using environment variables.
  • Using string concatenation for URLs with path parameters (prefer formatting).
  • Assuming synchronous HTTP calls in async contexts (e.g., Swift, Rust).

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 secret leakage in version control or logs.

Can I use a different HTTP client library?

Yes, but ensure it supports the same features (headers, JSON bodies, HTTPS) and idiomatic patterns for the language.

How do I handle pagination or rate limits?

Implement retry logic with exponential backoff and check response headers like 'Retry-After' or 'X-RateLimit-Remaining'.