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

Python · requests

import os
import requests

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

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

Python · httpx

import os
import httpx

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

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

Node.js · fetch

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

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

fetch(url, {
  method: 'PUT',
  headers,
  body: JSON.stringify(data)
})
  .then(res => {
    if (!res.ok) throw new Error(`HTTP error! status: ${res.status}`);
    return res.json();
  });

Node.js · axios

const axios = require('axios');

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

axios.put(url, data, { headers })
  .then(response => {
    if (response.status >= 400) throw new Error(`HTTP error! status: ${response.status}`);
  });

Go · net/http

package main

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

type RichText struct {
	Type string `json:"type"`
	Text struct {
		Content string `json:"content"`
	} `json:"text"`
}

type Paragraph struct {
	RichText []RichText `json:"rich_text"`
}

type Block struct {
	Object   string    `json:"object"`
	Type     string    `json:"type"`
	Paragraph Paragraph `json:"paragraph,omitempty"`
}

type RequestBody struct {
	Children []Block `json:"children"`
}

func main() {
	blockId := os.Getenv("BLOCK_ID")
	url := fmt.Sprintf("https://api.notion.com/v1/blocks/%s/children", blockId)
	token := os.Getenv("NOTION_TOKEN")

	body := RequestBody{
		Children: []Block{
			{
				Object: "block",
				Type:   "paragraph",
				Paragraph: Paragraph{
					RichText: []RichText{
						{
							Type: "text",
							Text: struct{ Content string `json:"content"` }{"Updated"},
						},
					},
				},
			},
		},
	}

	jsonData, _ := json.Marshal(body)
	req, _ := http.NewRequest("PUT", url, bytes.NewBuffer(jsonData))

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

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	if resp.StatusCode >= 400 {
		body, _ := io.ReadAll(resp.Body)
		panic(fmt.Sprintf("HTTP error! status: %d, body: %s", resp.StatusCode, body))
	}
}

PHP · cURL

<?php

$blockId = getenv('BLOCK_ID');
$url = "https://api.notion.com/v1/blocks/{$blockId}/children";
$token = getenv('NOTION_TOKEN');

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

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

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

if ($result === false) {
    throw new Exception("HTTP request failed");
}

$http_response = $http_response_header;
if (strpos($http_response[0], 'HTTP/') === 0 && substr($http_response[0], 9, 1) >= '4') {
    throw new Exception("HTTP error! status: " . substr($http_response[0], 9, 3));
}

Ruby · net/http

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

block_id = ENV['BLOCK_ID']
url = URI.parse("https://api.notion.com/v1/blocks/#{block_id}/children")
token = ENV['NOTION_TOKEN']

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

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Put.new(url.path, {
  'Authorization' => "Bearer #{token}",
  'Content-Type' => 'application/json',
  'Notion-Version' => '2022-06-28'
})
request.body = data.to_json

response = http.request(request)
if response.code.to_i >= 400
  raise "HTTP error! status: #{response.code}"
end

Swift · URLSession

import Foundation

let blockId = ProcessInfo.processInfo.environment["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_TOKEN"] ?? "")", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("2022-06-28", forHTTPHeaderField: "Notion-Version")

let body: [String: Any] = [
    "children": [
        [
            "object": "block",
            "type": "paragraph",
            "paragraph": [
                "rich_text": [
                    [
                        "type": "text",
                        "text": ["content": "Updated"]
                    ]
                ]
            ]
        ]
    ]
]

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

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    if let error = error {
        fatalError("Error: \(error)")
    }
    guard let httpResponse = response as? HTTPURLResponse else {
        fatalError("Invalid response")
    }
    if httpResponse.statusCode >= 400 {
        fatalError("HTTP error! status: \(httpResponse.statusCode)")
    }
}

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 = env::var("BLOCK_ID")?;
    let token = env::var("NOTION_TOKEN")?;
    let url = format!("https://api.notion.com/v1/blocks/{}/children", block_id);

    let client = Client::new();
    let body = json!({
        "children": [{
            "object": "block",
            "type": "paragraph",
            "paragraph": {
                "rich_text": [{
                    "type": "text",
                    "text": {"content": "Updated"}
                }]
            }
        }]
    });

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

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

    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 = Environment.GetEnvironmentVariable("BLOCK_ID");
        var token = Environment.GetEnvironmentVariable("NOTION_TOKEN");
        var url = new Uri($"https://api.notion.com/v1/blocks/{blockId}/children");

        var client = new HttpClient();
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
        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" }
                            }
                        }
                    }
                }
            }
        };

        var response = await client.PutAsJsonAsync(url, body);
        if (!response.IsSuccessStatusCode)
        {
            throw new Exception($"HTTP error! status: {response.StatusCode}");
        }
    }
}

Translation notes

  • All implementations read secrets from environment variables (NOTION_TOKEN, BLOCK_ID)
  • Python requests and httpx use the idiomatic json parameter for JSON bodies
  • Go uses structs to model the request body for type safety
  • PHP uses stream_context_create for simplicity
  • Ruby uses Net::HTTP with JSON serialization
  • Swift uses URLSession with async/await pattern
  • Rust uses reqwest blocking client for simplicity
  • C# uses HttpClient with PutAsJsonAsync for idiomatic JSON handling

Common pitfalls when porting

  • Forgetting to set BLOCK_ID or NOTION_TOKEN environment variables
  • Not handling HTTP errors properly (e.g., ignoring status codes)
  • JSON serialization issues due to incorrect struct/field names
  • Missing SSL/TLS configuration in Go or other low-level clients
  • Not setting Content-Type header explicitly in some languages

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 are the standard way to handle secrets in applications, avoiding hardcoding in source code and enabling different configurations across environments.

How do I handle pagination in Notion API?

The Notion API uses cursor-based pagination. Check the response for 'has_more' and use the 'next_cursor' value to fetch subsequent pages.

Why does the Go implementation use blocking client?

The example uses the blocking client for simplicity. In production Go code, you'd typically use the async client with proper error handling and context management.