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/pages/page_id -H "Authorization: Bearer secret_1234567890abcdef" -H "Content-Type: application/json" -d '{"properties":{"Title":{"title":[{"text":{"content":"Updated page"}}]}}'

Python · requests

import os
import requests

PAGE_ID = os.environ.get("NOTION_PAGE_ID")
API_KEY = os.environ.get("NOTION_API_KEY")

url = f"https://api.notion.com/v1/pages/{PAGE_ID}"
headers = {
    "Authorization": f"Bearer {API_KEY}",
    "Content-Type": "application/json",
    "Notion-Version": "2022-06-28"
}
data = {
    "properties": {
        "Title": {
            "title": [{"text": {"content": "Updated page"}}]
        }
    }
}

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

Python · httpx

import os
import httpx

PAGE_ID = os.environ.get("NOTION_PAGE_ID")
API_KEY = os.environ.get("NOTION_API_KEY")

url = f"https://api.notion.com/v1/pages/{PAGE_ID}"
headers = {
    "Authorization": f"Bearer {API_KEY}",
    "Content-Type": "application/json",
    "Notion-Version": "2022-06-28"
}
data = {
    "properties": {
        "Title": {
            "title": [{"text": {"content": "Updated page"}}]
        }
    }
}

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

Node.js · fetch

import fetch from 'node-fetch';

const PAGE_ID = process.env.NOTION_PAGE_ID;
const API_KEY = process.env.NOTION_API_KEY;

const url = `https://api.notion.com/v1/pages/${PAGE_ID}`;
const headers = {
  'Authorization': `Bearer ${API_KEY}`,
  'Content-Type': 'application/json',
  'Notion-Version': '2022-06-28'
};
const data = {
  properties: {
    Title: {
      title: [{ text: { content: 'Updated page' } }]
    }
  }
};

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();
  })
  .then(console.log)
  .catch(console.error);

Node.js · axios

import axios from 'axios';

const PAGE_ID = process.env.NOTION_PAGE_ID;
const API_KEY = process.env.NOTION_API_KEY;

const url = `https://api.notion.com/v1/pages/${PAGE_ID}`;
const headers = {
  'Authorization': `Bearer ${API_KEY}`,
  'Content-Type': 'application/json',
  'Notion-Version': '2022-06-28'
};
const data = {
  properties: {
    Title: {
      title: [{ text: { content: 'Updated page' } }]
    }
  }
};

axios.put(url, data, { headers })
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    if (error.response) {
      console.error('Error:', error.response.status, error.response.data);
    } else {
      console.error('Error:', error.message);
    }
  });

Go · net/http

package main

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

func main() {
	pageID := os.Getenv("NOTION_PAGE_ID")
	apiKey := os.Getenv("NOTION_API_KEY")

	url := fmt.Sprintf("https://api.notion.com/v1/pages/%s", pageID)
	requestBody := map[string]interface{}{
		"properties": map[string]interface{}{
			"Title": map[string]interface{}{
				"title": []map[string]interface{}{
					{"text": map[string]interface{}{"content": "Updated page"}},
				},
			},
		},
	}

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

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

	req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", apiKey))
	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 {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		body, _ := io.ReadAll(resp.Body)
		log.Fatalf("Request failed with status %d: %s", resp.StatusCode, string(body))
	}

	var result map[string]interface{}
	json.NewDecoder(resp.Body).Decode(&result)
	fmt.Println(result)
}

PHP · cURL

<?php

$pageId = getenv('NOTION_PAGE_ID');
$apiKey = getenv('NOTION_API_KEY');

$url = "https://api.notion.com/v1/pages/{$pageId}";
$data = [
    'properties' => [
        'Title' => [
            'title' => [
                ['text' => ['content' => 'Updated page']]
            ]
        ]
    ]
];

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

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

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

$response = json_decode($result, true);
print_r($response);

Ruby · net/http

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

page_id = ENV.fetch('NOTION_PAGE_ID')
api_key = ENV.fetch('NOTION_API_KEY')

uri = URI.parse("https://api.notion.com/v1/pages/#{page_id}")
request = Net::HTTP::Put.new(uri)
request['Authorization'] = "Bearer #{api_key}"
request['Content-Type'] = 'application/json'
request['Notion-Version'] = '2022-06-28'
request.body = {
  properties: {
    Title: {
      title: [{ text: { content: 'Updated page' } }]
    }
  }
}.to_json

http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
response = http.request(request)

unless response.is_a?(Net::HTTPSuccess)
  raise "Request failed: #{response.code} #{response.message}"
end

puts JSON.parse(response.body)

Swift · URLSession

import Foundation

guard let pageId = ProcessInfo.processInfo.environment["NOTION_PAGE_ID"] else {
    fatalError("NOTION_PAGE_ID environment variable not set")
}

guard let apiKey = ProcessInfo.processInfo.environment["NOTION_API_KEY"] else {
    fatalError("NOTION_API_KEY environment variable not set")
}

let url = URL(string: "https://api.notion.com/v1/pages/" + pageId)!
var request = URLRequest(url: url)
request.httpMethod = "PUT"
request.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("2022-06-28", forHTTPHeaderField: "Notion-Version")

let body: [String: Any] = [
    "properties": [
        "Title": [
            "title": [
                ["text": ["content": "Updated page"]]
            ]
        ]
    ]
]

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

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    if let error = error {
        fatalError("Request failed: \(error)")
    }

    guard let httpResponse = response as? HTTPURLResponse else {
        fatalError("Invalid response")
    }

    guard (200...299).contains(httpResponse.statusCode) else {
        fatalError("Request failed with status code: \(httpResponse.statusCode)")
    }

    if let data = data, let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
        print(json)
    }
}

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 page_id = env::var("NOTION_PAGE_ID")?;
    let api_key = env::var("NOTION_API_KEY")?;

    let url = format!("https://api.notion.com/v1/pages/{}", page_id);
    let client = Client::new();
    let body = json!({
        "properties": {
            "Title": {
                "title": [{"text": {"content": "Updated page"}}]
            }
        }
    });

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

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

    let json: serde_json::Value = response.json()?;
    println!("{}", json);
    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 pageId = Environment.GetEnvironmentVariable("NOTION_PAGE_ID");
        var apiKey = Environment.GetEnvironmentVariable("NOTION_API_KEY");

        var url = $"https://api.notion.com/v1/pages/{pageId}";
        var client = new HttpClient();
        var request = new HttpRequestMessage(HttpMethod.Put, url);

        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
        request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        request.Headers.Add("Notion-Version", "2022-06-28");

        var body = new
        {
            properties = new
            {
                Title = new
                {
                    title = new[]
                    {
                        new
                        {
                            text = new { content = "Updated page" }
                        }
                    }
                }
            }
        };

        request.Content = new StringContent(JsonSerializer.Serialize(body));
        request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

        var response = await client.SendAsync(request);
        response.EnsureSuccessStatusCode();

        var responseBody = await response.Content.ReadAsStringAsync();
        Console.WriteLine(responseBody);
    }
}

Translation notes

  • All implementations use environment variables for secrets (NOTION_PAGE_ID, NOTION_API_KEY).
  • The Notion-Version header is added as it's required by the Notion API.
  • Python, Node.js, Go, Ruby, Swift, Rust, and C# use idiomatic HTTP clients.
  • PHP uses file_get_contents with stream context for simplicity.
  • Error handling checks HTTP status and reads response body on failure.

Common pitfalls when porting

  • Forgetting to set NOTION_PAGE_ID and NOTION_API_KEY environment variables.
  • Omitting the Notion-Version header which is required by the API.
  • Not handling JSON serialization/deserialization correctly in strongly-typed languages.
  • Ignoring HTTPS errors in Go or Swift (not shown here but common in production).

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 is the Notion-Version header required?

The Notion API requires a version header to ensure compatibility. The version '2022-06-28' is used here as an example.

Can I use a raw string for the JSON body instead of a structured object?

Yes, but using structured objects (like in the examples) is safer and more maintainable. Raw strings require manual escaping and validation.