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_abc123def456ghi789jkl012mno345" \
  -H "Notion-Version: 2022-06-28" \
  -d '{"children":[{"object":"block","type":"paragraph","paragraph":{"rich_text":[{"type":"text","text":{"content":"Updated 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"
}
data = {
    "children": [{
        "object": "block",
        "type": "paragraph",
        "paragraph": {
            "rich_text": [{
                "type": "text",
                "text": {"content": "Updated text"}
            }]
        }
    }]
}

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

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"
}
data = {
    "children": [{
        "object": "block",
        "type": "paragraph",
        "paragraph": {
            "rich_text": [{
                "type": "text",
                "text": {"content": "Updated text"}
            }]
        }
    }]
}

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

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'
};
const data = {
  children: [{
    object: 'block',
    type: 'paragraph',
    paragraph: {
      rich_text: [{
        type: 'text',
        text: { content: 'Updated text' }
      }]
    }
  }]
};

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

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'
};
const data = {
  children: [{
    object: 'block',
    type: 'paragraph',
    paragraph: {
      rich_text: [{
        type: 'text',
        text: { content: 'Updated text' }
      }]
    }
  }]
};

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

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 text",
							},
						},
					},
				},
			},
		},
	}
	
	bodyBytes, _ := json.Marshal(requestBody)
	req, _ := http.NewRequest("PUT", url, bytes.NewBuffer(bodyBytes))
	
	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("Error:", err)
		return
	}
	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

$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 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);
$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'

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 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
else
  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 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
    }
    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 std::env;
use reqwest::blocking::Client;
use serde_json::json;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let block_id = "block_id";
    let url = format!("https://api.notion.com/v1/blocks/{}/children", block_id);
    
    let client = Client::new();
    let response = client
        .put(&url)
        .header("Authorization", format!("Bearer {}", env::var("NOTION_API_KEY")?))
        .header("Notion-Version", "2022-06-28")
        .json(&json!({
            "children": [{
                "object": "block",
                "type": "paragraph",
                "paragraph": {
                    "rich_text": [{
                        "type": "text",
                        "text": {"content": "Updated text"}
                    }]
                }
            }]
        }))
        .send()?;

    if response.status().as_u16() >= 400 {
        println!("{}", response.text()?);
    } else {
        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 blockId = "block_id";
        var url = new Uri($"https://api.notion.com/v1/blocks/{blockId}/children");
        
        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 text" }
                            }
                        }
                    }
                }
            }
        };
        
        var response = await client.PutAsJsonAsync(url, body);
        
        if (!response.IsSuccessStatusCode)
        {
            var errorContent = await response.Content.ReadAsStringAsync();
            Console.WriteLine(errorContent);
        }
        else
        {
            var content = await response.Content.ReadAsStringAsync();
            Console.WriteLine(content);
        }
    }
}

Translation notes

  • All implementations use environment variables for secrets (NOTION_API_KEY)
  • Python requests and httpx use the 'json' parameter for automatic serialization
  • Go uses a map[string]interface{} for dynamic JSON construction
  • Swift uses URLSession for async requests (requires RunLoop for synchronous example)
  • Rust uses reqwest blocking client for simplicity in the example
  • C# uses HttpClient with PutAsJsonAsync for idiomatic JSON handling

Common pitfalls when porting

  • Forgetting to set Content-Type header in Go/PHP/Ruby may cause API to reject the request
  • In Swift, environment variables must be set before runtime (e.g., in launch arguments)
  • In Rust, the blocking client is used for simplicity; async would require tokio runtime
  • In Node.js, fetch/axios may require additional polyfills in older environments
  • In Python, requests/httpx may need to handle SSL verification explicitly in some environments

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 prevent secrets from being committed to version control and allow different configurations across environments (dev, staging, prod).

How do I handle pagination or large responses in these clients?

Most clients provide streaming or pagination helpers. For example, in Python requests you can use `response.iter_content()` for large downloads.

Can I use async/await in all these languages?

Yes, but the examples use synchronous code for simplicity. Async versions would require language-specific async/await syntax (e.g., async/await in C#, asyncio in Python, async/await in Swift).