Code Examples
Complete code examples for using the Entity Detector API in multiple programming languages.
Note: All examples use environment variables for the API key. Never hardcode API keys in your source code.
cURL
Quick testing from the command line:
bash
curl -X POST https://api.entitydetector.com/v1/analyze \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_TOKEN" \
-d '{
"text": "Apple CEO Tim Cook announced the iPhone 15 launch in Cupertino, California. The new device features a USB-C port.",
"options": {
"includeEvidence": true
}
}'TypeScript
Fully typed example with interfaces:
typescript
interface AnalyzeOptions {
languageHint?: string;
maxEntitiesPerType?: number;
includeEvidence?: boolean;
}
interface Relation {
source: string;
target: string;
type: string;
evidence: string;
sentiment: 'positive' | 'negative' | 'neutral';
confidence: number;
}
interface AnalyzeResult {
entities: {
persons: string[];
organizations: string[];
locations: string[];
objects: string[];
};
relations: Relation[];
meta: {
model: string;
language: string;
processingMs: number;
cached: boolean;
};
}
async function analyzeText(
text: string,
options?: AnalyzeOptions
): Promise<AnalyzeResult> {
const response = await fetch('https://api.entitydetector.com/v1/analyze', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${process.env.ENTITY_DETECTOR_API_KEY}`
},
body: JSON.stringify({ text, options })
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.message);
}
return response.json();
}
// Usage
const result = await analyzeText('Your article text here...', {
includeEvidence: true
});
// Type-safe access
result.entities.persons.forEach(person => {
console.log(`Person: ${person}`);
});
result.relations.forEach(relation => {
console.log(`${relation.source} --[${relation.type}]--> ${relation.target}`);
});Node.js
Using native fetch (Node.js 18+):
javascript
// Using fetch (Node.js 18+)
async function analyzeText(text) {
const response = await fetch('https://api.entitydetector.com/v1/analyze', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${process.env.ENTITY_DETECTOR_API_KEY}`
},
body: JSON.stringify({
text,
options: {
includeEvidence: true
}
})
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.message);
}
return response.json();
}
// Usage
const result = await analyzeText('Your article text here...');
console.log('Entities:', result.entities);
console.log('Relations:', result.relations);Python
Using the requests library:
python
import os
import requests
def analyze_text(text: str) -> dict:
"""Analyze text and extract entities using Entity Detector API."""
response = requests.post(
'https://api.entitydetector.com/v1/analyze',
headers={
'Content-Type': 'application/json',
'Authorization': f'Bearer {os.environ["ENTITY_DETECTOR_API_KEY"]}'
},
json={
'text': text,
'options': {
'includeEvidence': True
}
}
)
response.raise_for_status()
return response.json()
# Usage
result = analyze_text('Your article text here...')
print('Entities:', result['entities'])
print('Relations:', result['relations'])Go
Using the standard library:
go
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"os"
)
type AnalyzeRequest struct {
Text string `json:"text"`
Options *AnalyzeOptions `json:"options,omitempty"`
}
type AnalyzeOptions struct {
LanguageHint string `json:"languageHint,omitempty"`
MaxEntitiesPerType int `json:"maxEntitiesPerType,omitempty"`
IncludeEvidence bool `json:"includeEvidence,omitempty"`
}
type AnalyzeResponse struct {
Entities map[string][]string `json:"entities"`
Relations []Relation `json:"relations"`
Meta Meta `json:"meta"`
}
type Relation struct {
Source string `json:"source"`
Target string `json:"target"`
Type string `json:"type"`
Evidence string `json:"evidence"`
Sentiment string `json:"sentiment"`
Confidence float64 `json:"confidence"`
}
type Meta struct {
Model string `json:"model"`
Language string `json:"language"`
ProcessingMs int `json:"processingMs"`
Cached bool `json:"cached"`
}
func analyzeText(text string) (*AnalyzeResponse, error) {
reqBody := AnalyzeRequest{
Text: text,
Options: &AnalyzeOptions{
IncludeEvidence: true,
},
}
jsonBody, err := json.Marshal(reqBody)
if err != nil {
return nil, err
}
req, err := http.NewRequest(
"POST",
"https://api.entitydetector.com/v1/analyze",
bytes.NewBuffer(jsonBody),
)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+os.Getenv("ENTITY_DETECTOR_API_KEY"))
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var result AnalyzeResponse
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return nil, err
}
return &result, nil
}
func main() {
result, err := analyzeText("Your article text here...")
if err != nil {
panic(err)
}
fmt.Printf("Entities: %v\n", result.Entities)
}PHP
Using cURL:
php
<?php
function analyzeText(string $text): array {
$apiKey = getenv('ENTITY_DETECTOR_API_KEY');
$ch = curl_init('https://api.entitydetector.com/v1/analyze');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Authorization: Bearer ' . $apiKey
],
CURLOPT_POSTFIELDS => json_encode([
'text' => $text,
'options' => [
'includeEvidence' => true
]
])
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode !== 200) {
throw new Exception('API request failed: ' . $response);
}
return json_decode($response, true);
}
// Usage
$result = analyzeText('Your article text here...');
print_r($result['entities']);
print_r($result['relations']);Ruby
Using Net::HTTP:
ruby
require 'net/http'
require 'json'
require 'uri'
def analyze_text(text)
uri = URI('https://api.entitydetector.com/v1/analyze')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Post.new(uri)
request['Content-Type'] = 'application/json'
request['Authorization'] = "Bearer #{ENV['ENTITY_DETECTOR_API_KEY']}"
request.body = {
text: text,
options: {
includeEvidence: true
}
}.to_json
response = http.request(request)
unless response.is_a?(Net::HTTPSuccess)
raise "API request failed: #{response.body}"
end
JSON.parse(response.body)
end
# Usage
result = analyze_text('Your article text here...')
puts "Entities: #{result['entities']}"
puts "Relations: #{result['relations']}"Language Support
The API accepts text in any language. You can optionally provide a language hint to improve accuracy:
json
{
"text": "Der Bundeskanzler Olaf Scholz traf sich in Berlin mit dem französischen Präsidenten Emmanuel Macron.",
"options": {
"languageHint": "de"
}
}Batch Processing
For processing multiple texts, send separate requests. We recommend using a rate limiter to stay within your quota:
javascript
// Process multiple texts with rate limiting
async function batchAnalyze(texts, delayMs = 200) {
const results = [];
for (const text of texts) {
const result = await analyzeText(text);
results.push(result);
// Add delay between requests
await new Promise(r => setTimeout(r, delayMs));
}
return results;
}
const texts = [
'First article text...',
'Second article text...',
'Third article text...'
];
const results = await batchAnalyze(texts);