import os
import requests
NOTION_API_KEY = os.environ.get("NOTION_API_KEY")
NOTION_VERSION = os.environ.get("NOTION_VERSION", "2022-06-28")
response = requests.get(
f"https://api.notion.com/v1/databases/{os.environ.get('DATABASE_ID')}/query",
headers={
"Authorization": f"Bearer {NOTION_API_KEY}",
"Notion-Version": NOTION_VERSION
}
)
if response.status_code >= 400:
print(f"Error: {response.status_code} - {response.text}")
else:
print(response.json())
import os
import httpx
NOTION_API_KEY = os.environ.get("NOTION_API_KEY")
NOTION_VERSION = os.environ.get("NOTION_VERSION", "2022-06-28")
async def query_database():
async with httpx.AsyncClient() as client:
response = await client.get(
f"https://api.notion.com/v1/databases/{os.environ.get('DATABASE_ID')}/query",
headers={
"Authorization": f"Bearer {NOTION_API_KEY}",
"Notion-Version": NOTION_VERSION
}
)
if response.status_code >= 400:
print(f"Error: {response.status_code} - {response.text}")
else:
print(response.json())
# For synchronous usage:
# with httpx.Client() as client:
# response = client.get(...)
# ...
const fetch = require('node-fetch');
const NOTION_API_KEY = process.env.NOTION_API_KEY;
const NOTION_VERSION = process.env.NOTION_VERSION || '2022-06-28';
const DATABASE_ID = process.env.DATABASE_ID;
fetch(`https://api.notion.com/v1/databases/${DATABASE_ID}/query`, {
method: 'GET',
headers: {
'Authorization': `Bearer ${NOTION_API_KEY}`,
'Notion-Version': NOTION_VERSION
}
})
.then(response => {
if (!response.ok) {
throw new Error(`Error: ${response.status} - ${response.statusText}`);
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error(error));
const axios = require('axios');
const NOTION_API_KEY = process.env.NOTION_API_KEY;
const NOTION_VERSION = process.env.NOTION_VERSION || '2022-06-28';
const DATABASE_ID = process.env.DATABASE_ID;
axios.get(`https://api.notion.com/v1/databases/${DATABASE_ID}/query`, {
headers: {
'Authorization': `Bearer ${NOTION_API_KEY}`,
'Notion-Version': NOTION_VERSION
}
})
.then(response => {
if (response.status >= 400) {
throw new Error(`Error: ${response.status} - ${response.statusText}`);
}
console.log(response.data);
})
.catch(error => console.error(error));
package main
import (
"fmt"
"io"
"log"
"net/http"
"os"
)
func main() {
notionAPIKey := os.Getenv("NOTION_API_KEY")
notionVersion := os.Getenv("NOTION_VERSION")
if notionVersion == "" {
notionVersion = "2022-06-28"
}
databaseID := os.Getenv("DATABASE_ID")
client := &http.Client{}
req, err := http.NewRequest(
"GET",
fmt.Sprintf("https://api.notion.com/v1/databases/%s/query", databaseID),
nil,
)
if err != nil {
log.Fatal(err)
}
req.Header.Set("Authorization", "Bearer "+notionAPIKey)
req.Header.Set("Notion-Version", notionVersion)
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
body, _ := io.ReadAll(resp.Body)
log.Fatalf("Error: %d - %s", resp.StatusCode, string(body))
}
body, _ := io.ReadAll(resp.Body)
fmt.Println(string(body))
}
<?php
$notionAPIKey = getenv('NOTION_API_KEY');
$notionVersion = getenv('NOTION_VERSION') ?: '2022-06-28';
$databaseID = getenv('DATABASE_ID');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.notion.com/v1/databases/{$databaseID}/query");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $notionAPIKey,
'Notion-Version: ' . $notionVersion
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode >= 400) {
throw new Exception("Error: {$httpCode} - {$response}");
}
print_r(json_decode($response, true));
require 'net/http'
require 'json'
notion_api_key = ENV['NOTION_API_KEY']
notion_version = ENV['NOTION_VERSION'] || '2022-06-28'
database_id = ENV['DATABASE_ID']
uri = URI.parse("https://api.notion.com/v1/databases/#{database_id}/query")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Get.new(uri.request_uri)
request['Authorization'] = "Bearer #{notion_api_key}"
request['Notion-Version'] = notion_version
response = http.request(request)
if response.code.to_i >= 400
puts "Error: #{response.code} - #{response.body}"
else
puts JSON.parse(response.body)
end
import Foundation
let notionAPIKey = ProcessInfo.processInfo.environment["NOTION_API_KEY"] ?? ""
let notionVersion = ProcessInfo.processInfo.environment["NOTION_VERSION"] ?? "2022-06-28"
let databaseID = ProcessInfo.processInfo.environment["DATABASE_ID"] ?? ""
let url = URL(string: "https://api.notion.com/v1/databases/" + databaseID + "/query")!
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.setValue("Bearer " + notionAPIKey, forHTTPHeaderField: "Authorization")
request.setValue(notionVersion, forHTTPHeaderField: "Notion-Version")
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 >= 400 else {
return
}
if let data = data, let responseBody = String(data: data, encoding: .utf8) {
print("Error: \(httpResponse.statusCode) - \(responseBody)")
}
}
task.resume()
// For synchronous usage:
// let (data, response) = try await URLSession.shared.data(for: request)
// if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode >= 400 {
// print("Error: \(httpResponse.statusCode) - \(String(data: data, encoding: .utf8) ?? "")")
// } else {
// print(String(data: data, encoding: .utf8) ?? "")
// }
use std::env;
use reqwest;
use tokio;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let notion_api_key = env::var("NOTION_API_KEY")?;
let notion_version = env::var("NOTION_VERSION").unwrap_or_else(|_| "2022-06-28".to_string());
let database_id = env::var("DATABASE_ID")?;
let client = reqwest::Client::new();
let response = client
.get(format!("https://api.notion.com/v1/databases/{}/query", database_id))
.header("Authorization", format!("Bearer {}", notion_api_key))
.header("Notion-Version", notion_version)
.send()
.await?;
if !response.status().is_success() {
let status = response.status();
let body = response.text().await?;
eprintln!("Error: {} - {}", status, body);
} else {
let body = response.text().await?;
println!("{}", body);
}
Ok(())
}
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
var notionAPIKey = Environment.GetEnvironmentVariable("NOTION_API_KEY");
var notionVersion = Environment.GetEnvironmentVariable("NOTION_VERSION") ?? "2022-06-28";
var databaseID = Environment.GetEnvironmentVariable("DATABASE_ID");
using var client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {notionAPIKey}");
client.DefaultRequestHeaders.Add("Notion-Version", notionVersion);
var response = await client.GetAsync($"https://api.notion.com/v1/databases/{databaseID}/query");
if (!response.IsSuccessStatusCode)
{
var errorContent = await response.Content.ReadAsStringAsync();
Console.WriteLine($"Error: {response.StatusCode} - {errorContent}");
}
else
{
var content = await response.Content.ReadAsStringAsync();
Console.WriteLine(content);
}
}
}