API Usage Examples
Code examples for using the Typespace API in different programming languages
API Usage Examples
This page provides code examples for using the Typespace API in various programming languages.
Prerequisites
Before using these examples, make sure you have:
- A Typespace account
- Your Space API Key (available at typespace.app/write)
- A brand ID from your Typespace account
JavaScript / Node.js
Using Fetch API
async function generateContent() {
const response = await fetch('https://typespace.app/api/generate', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Space-API-Key': 'your_api_key_here'
},
body: JSON.stringify({
brandId: 'your_brand_id',
options: {
targetPlatform: 'LinkedIn',
subject: 'The future of AI in content marketing',
emojiUsage: 'few',
shouldStream: false
}
})
});
const data = await response.json();
console.log(data);
return data;
}
generateContent();
Streaming Response with Node.js
const https = require('https');
function generateContentStream() {
return new Promise((resolve, reject) => {
const data = JSON.stringify({
brandId: 'your_brand_id',
options: {
targetPlatform: 'LinkedIn',
subject: 'The future of AI in content marketing',
emojiUsage: 'few',
shouldStream: true
}
});
const options = {
hostname: 'typespace.app',
path: '/api/generate',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Space-API-Key': 'your_api_key_here',
'Content-Length': data.length
}
};
const req = https.request(options, (res) => {
let content = '';
res.on('data', (chunk) => {
const chunkStr = chunk.toString();
console.log(chunkStr); // Process each chunk as it arrives
content += chunkStr;
});
res.on('end', () => {
resolve(content);
});
});
req.on('error', (error) => {
reject(error);
});
req.write(data);
req.end();
});
}
generateContentStream()
.then(result => console.log('Final content:', result))
.catch(error => console.error('Error:', error));
Python
import requests
import json
def generate_content():
url = "https://typespace.app/api/generate"
headers = {
"Content-Type": "application/json",
"X-Space-API-Key": "your_api_key_here"
}
payload = {
"brandId": "your_brand_id",
"options": {
"targetPlatform": "LinkedIn",
"subject": "The future of AI in content marketing",
"emojiUsage": "few",
"shouldStream": False
}
}
response = requests.post(url, headers=headers, data=json.dumps(payload))
if response.status_code == 200:
return response.json()
else:
print(f"Error: {response.status_code}")
print(response.text)
return None
result = generate_content()
print(result)
Streaming Response with Python
import requests
import json
def generate_content_stream():
url = "https://typespace.app/api/generate"
headers = {
"Content-Type": "application/json",
"X-Space-API-Key": "your_api_key_here"
}
payload = {
"brandId": "your_brand_id",
"options": {
"targetPlatform": "LinkedIn",
"subject": "The future of AI in content marketing",
"emojiUsage": "few",
"shouldStream": True
}
}
with requests.post(url, headers=headers, data=json.dumps(payload), stream=True) as response:
if response.status_code == 200:
content = ""
for chunk in response.iter_content(chunk_size=1024):
if chunk:
chunk_str = chunk.decode('utf-8')
print(chunk_str, end='') # Process each chunk as it arrives
content += chunk_str
return content
else:
print(f"Error: {response.status_code}")
print(response.text)
return None
result = generate_content_stream()
print("\nFinal content:", result)
Ruby
require 'net/http'
require 'uri'
require 'json'
def generate_content
uri = URI('https://typespace.app/api/generate')
headers = {
'Content-Type' => 'application/json',
'X-Space-API-Key' => 'your_api_key_here'
}
payload = {
brandId: 'your_brand_id',
options: {
targetPlatform: 'LinkedIn',
subject: 'The future of AI in content marketing',
emojiUsage: 'few',
shouldStream: false
}
}
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Post.new(uri.path, headers)
request.body = payload.to_json
response = http.request(request)
if response.code == '200'
return JSON.parse(response.body)
else
puts "Error: #{response.code}"
puts response.body
return nil
end
end
result = generate_content
puts result
PHP
<?php
function generateContent() {
$url = "https://typespace.app/api/generate";
$headers = [
"Content-Type: application/json",
"X-Space-API-Key: your_api_key_here"
];
$payload = [
"brandId" => "your_brand_id",
"options" => [
"targetPlatform" => "LinkedIn",
"subject" => "The future of AI in content marketing",
"emojiUsage" => "few",
"shouldStream" => false
]
];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode == 200) {
return json_decode($response, true);
} else {
echo "Error: " . $httpCode . "\n";
echo $response . "\n";
return null;
}
}
$result = generateContent();
print_r($result);
?>
Common Use Cases
Improving an Existing Post
// JavaScript example
async function improvePost() {
const response = await fetch('https://typespace.app/api/generate', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Space-API-Key': 'your_api_key_here'
},
body: JSON.stringify({
brandId: 'your_brand_id',
options: {
postId: 'existing_post_id',
improve: true,
additionalContext: 'Make it more persuasive and add a call to action',
shouldStream: false
}
})
});
const data = await response.json();
console.log(data);
return data;
}
Generating Content Based on a URL
// JavaScript example
async function generateFromUrl() {
const response = await fetch('https://typespace.app/api/generate', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Space-API-Key': 'your_api_key_here'
},
body: JSON.stringify({
brandId: 'your_brand_id',
options: {
targetPlatform: 'X',
topicSource: 'url',
url: 'https://example.com/article-to-reference',
deepResearchSource: true,
shouldStream: false
}
})
});
const data = await response.json();
console.log(data);
return data;
}
Creating a Thread or Carousel
// JavaScript example
async function generateThread() {
const response = await fetch('https://typespace.app/api/generate', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Space-API-Key': 'your_api_key_here'
},
body: JSON.stringify({
brandId: 'your_brand_id',
options: {
targetPlatform: 'X',
subject: 'Tips for effective remote work',
createCarouselsOrThread: true,
shouldStream: false
}
})
});
const data = await response.json();
console.log(data);
return data;
}
Error Handling
Always implement proper error handling in your API calls:
// JavaScript example
async function generateWithErrorHandling() {
try {
const response = await fetch('https://typespace.app/api/generate', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Space-API-Key': 'your_api_key_here'
},
body: JSON.stringify({
brandId: 'your_brand_id',
options: {
targetPlatform: 'LinkedIn',
subject: 'The future of AI in content marketing'
}
})
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`API error (${response.status}): ${errorText}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error('Error generating content:', error);
// Handle error appropriately
return null;
}
}