import os
import requests
url = f"https://api.notion.com/v1/databases/{os.environ['DATABASE_ID']}"
headers = {
"Authorization": f"Bearer {os.environ['NOTION_API_KEY']}",
"Notion-Version": "2022-06-28",
"Content-Type": "application/json"
}
data = {
"properties": {"Name": {"title": {}}},
"title": "Updated Database"
}
response = requests.put(url, headers=headers, json=data)
response.raise_for_status()
print(response.json())
import os
import httpx
url = f"https://api.notion.com/v1/databases/{os.environ['DATABASE_ID']}"
headers = {
"Authorization": f"Bearer {os.environ['NOTION_API_KEY']}",
"Notion-Version": "2022-06-28",
"Content-Type": "application/json"
}
data = {
"properties": {"Name": {"title": {}}},
"title": "Updated Database"
}
with httpx.Client() as client:
response = client.put(url, headers=headers, json=data)
response.raise_for_status()
print(response.json())
import fetch from 'node-fetch';
import { DATABASE_ID, NOTION_API_KEY } from './config.js';
const url = `https://api.notion.com/v1/databases/${DATABASE_ID}`;
const headers = {
'Authorization': `Bearer ${NOTION_API_KEY}`,
'Notion-Version': '2022-06-28',
'Content-Type': 'application/json'
};
const data = {
properties: { Name: { title: {} } },
title: 'Updated Database'
};
try {
const response = await fetch(url, {
method: 'PUT',
headers,
body: JSON.stringify(data)
});
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
const json = await response.json();
console.log(json);
} catch (error) {
console.error('Error:', error);
}
import axios from 'axios';
import { DATABASE_ID, NOTION_API_KEY } from './config.js';
const url = `https://api.notion.com/v1/databases/${DATABASE_ID}`;
const headers = {
'Authorization': `Bearer ${NOTION_API_KEY}`,
'Notion-Version': '2022-06-28',
'Content-Type': 'application/json'
};
const data = {
properties: { Name: { title: {} } },
title: 'Updated Database'
};
try {
const response = await axios.put(url, data, { headers });
console.log(response.data);
} catch (error) {
if (error.response) {
console.error('Error:', error.response.status, error.response.data);
} else {
console.error('Error:', error.message);
}
}
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
type DatabaseUpdate struct {
Properties map[string]interface{} `json:"properties"`
Title string `json:"title"`
}
func main() {
url := fmt.Sprintf("https://api.notion.com/v1/databases/%s", os.Getenv("DATABASE_ID"))
apiKey := os.Getenv("NOTION_API_KEY")
data := DatabaseUpdate{
Properties: map[string]interface{}{
"Name": map[string]interface{}{
"title": map[string]interface{}{},
},
},
Title: "Updated Database",
}
jsonData, _ := json.Marshal(data)
req, err := http.NewRequest("PUT", url, bytes.NewBuffer(jsonData))
if err != nil {
fmt.Println("Error creating request:", err)
return
}
req.Header.Set("Authorization", "Bearer "+apiKey)
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 making request:", err)
return
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
if resp.StatusCode != http.StatusOK {
fmt.Printf("Error: %s\nBody: %s\n", resp.Status, body)
return
}
fmt.Println(string(body))
}
<?php
$url = 'https://api.notion.com/v1/databases/' . urlencode(getenv('DATABASE_ID'));
$apiKey = getenv('NOTION_API_KEY');
$data = [
'properties' => [
'Name' => [
'title' => []
]
],
'title' => 'Updated Database'
];
$options = [
'http' => [
'method' => 'PUT',
'header' => [
'Authorization: Bearer ' . $apiKey,
'Notion-Version: 2022-06-28',
'Content-Type: application/json'
],
'content' => json_encode($data)
]
];
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
if ($response === false) {
throw new Exception('Request failed');
}
$httpResponse = $http_response_header;
if (strpos($httpResponse[0], 'HTTP/') === 0 && strpos($httpResponse[0], '200') === false) {
throw new Exception('HTTP error: ' . $httpResponse[0]);
}
print_r(json_decode($response, true));
require 'net/http'
require 'json'
require 'uri'
url = URI.parse("https://api.notion.com/v1/databases/#{ENV['DATABASE_ID']}")
api_key = ENV['NOTION_API_KEY']
request = Net::HTTP::Put.new(url.path, {
'Authorization' => "Bearer #{api_key}",
'Notion-Version' => '2022-06-28',
'Content-Type' => 'application/json'
})
request.body = {
properties: { Name: { title: {} } },
title: 'Updated Database'
}.to_json
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
response = http.request(request)
unless response.is_a?(Net::HTTPSuccess)
raise "HTTP error: #{response.code} #{response.message}"
end
puts JSON.parse(response.body)
import Foundation
let databaseId = ProcessInfo.processInfo.environment["DATABASE_ID"] ?? ""
let apiKey = ProcessInfo.processInfo.environment["NOTION_API_KEY"] ?? ""
let url = URL(string: "https://api.notion.com/v1/databases/" + databaseId)!
var request = URLRequest(url: url)
request.httpMethod = "PUT"
request.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")
request.setValue("2022-06-28", forHTTPHeaderField: "Notion-Version")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let body: [String: Any] = [
"properties": ["Name": ["title": []]],
"title": "Updated Database"
]
request.httpBody = try JSONSerialization.data(withJSONObject: body)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error {
print("Error: \(error)")
return
}
guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
print("HTTP error: \((response as? HTTPURLResponse)?.statusCode ?? 0)")
return
}
if let data = data, let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
print(json)
}
}
task.resume()
RunLoop.main.run()
use std::env;
use reqwest::blocking::Client;
use serde_json::json;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let database_id = env::var("DATABASE_ID")?;
let api_key = env::var("NOTION_API_KEY")?;
let url = format!("https://api.notion.com/v1/databases/{}", database_id);
let client = Client::new();
let body = json!({
"properties": {"Name": {"title": {}}},
"title": "Updated Database"
});
let response = client
.put(&url)
.header("Authorization", format!("Bearer {}", api_key))
.header("Notion-Version", "2022-06-28")
.header("Content-Type", "application/json")
.json(&body)
.send()?;
if !response.status().is_success() {
return Err(format!("HTTP error: {}", response.status()).into());
}
let json: serde_json::Value = response.json()?;
println!("{}", json);
Ok(())
}
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 databaseId = Environment.GetEnvironmentVariable("DATABASE_ID");
var apiKey = Environment.GetEnvironmentVariable("NOTION_API_KEY");
var url = $"https://api.notion.com/v1/databases/{databaseId}";
var client = new HttpClient();
var body = new
{
properties = new
{
Name = new { title = new object[] { } }
},
title = "Updated Database"
};
var request = new HttpRequestMessage(HttpMethod.Put, url)
{
Content = new StringContent(JsonSerializer.Serialize(body))
{
Headers = { ContentType = new MediaTypeHeaderValue("application/json") }
}
};
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
request.Headers.Add("Notion-Version", "2022-06-28");
var response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}