REST API Guide
Direct HTTP API usage without SDKs. Perfect for any programming language or tool that supports HTTP requests.
๐ Base URLโ
https://api.usecortex.co/v1
๐ Authenticationโ
All requests require an API key in the Authorization header:
Authorization: Bearer cortex_sk_your_api_key_here
Alternative header format:
X-API-Key: cortex_sk_your_api_key_here
๐ Request Formatโ
Content Typeโ
All POST requests must include:
Content-Type: application/json
Standard Headersโ
curl -X POST https://api.usecortex.co/v1/search \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-H "User-Agent: YourApp/1.0" \
-d '{"query": "your search query"}'
๐ Search Endpointโ
POST /v1/searchโ
Basic Requestโ
curl -X POST https://api.usecortex.co/v1/search \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"query": "latest AI developments"
}'
Advanced Requestโ
curl -X POST https://api.usecortex.co/v1/search \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"query": "Tesla stock analysis Q4 2024",
"max_results": 8,
"language": "en",
"country": "us",
"recency": "week",
"format": "json",
"include_sources": true,
"domain_filter": {
"include": ["reuters.com", "bloomberg.com", "cnbc.com"],
"exclude": ["reddit.com", "twitter.com"]
},
"options": {
"enable_cache": true,
"timeout": 15,
"deep_search": false
}
}'
Response Exampleโ
{
"success": true,
"data": {
"summary": "Tesla's Q4 2024 performance showed strong delivery numbers...",
"sources": [
{
"url": "https://reuters.com/business/tesla-q4-results",
"title": "Tesla Q4 2024 Results Beat Expectations",
"snippet": "Tesla delivered record numbers in Q4...",
"confidence": 0.94,
"published_date": "2025-01-08T10:00:00Z",
"domain": "reuters.com"
}
],
"metadata": {
"query_time": 2.34,
"sources_analyzed": 8,
"confidence_score": 0.91
}
},
"request_id": "req_search_123abc"
}
๐ Extract Endpointโ
POST /v1/extractโ
Basic Requestโ
curl -X POST https://api.usecortex.co/v1/extract \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"url": "https://example.com/article"
}'
Advanced Requestโ
curl -X POST https://api.usecortex.co/v1/extract \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"url": "https://techcrunch.com/ai-article",
"format": "markdown",
"include_metadata": true,
"extract_images": true,
"extract_links": false,
"clean_html": true,
"options": {
"timeout": 20,
"preserve_formatting": true,
"min_content_length": 100
}
}'
Response Exampleโ
{
"success": true,
"data": {
"content": "# Article Title\n\nThis is the clean extracted content...",
"metadata": {
"title": "Article Title",
"author": "John Smith",
"published_date": "2025-01-08T15:30:00Z",
"word_count": 1250,
"reading_time": "6 min read",
"language": "en"
},
"images": [
{
"url": "https://example.com/image.jpg",
"alt": "Article image",
"caption": "Image caption"
}
],
"quality_score": 0.89
},
"request_id": "req_extract_456def"
}
โ Validate Endpointโ
POST /v1/validateโ
Basic Requestโ
curl -X POST https://api.usecortex.co/v1/validate \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"claim": "The iPhone 15 was released in September 2023"
}'
Advanced Requestโ
curl -X POST https://api.usecortex.co/v1/validate \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"claim": "Tesla delivered over 1.8 million vehicles in 2023",
"sources": [
"https://ir.tesla.com/press-release/tesla-q4-2023",
"reuters.com",
"bloomberg.com"
],
"context": {
"domain": "automotive",
"claim_type": "statistical",
"time_sensitive": true
},
"options": {
"confidence_threshold": 0.8,
"require_primary_sources": true,
"max_sources": 10,
"timeout": 20
}
}'
Response Exampleโ
{
"success": true,
"data": {
"validation_result": "VERIFIED",
"confidence_score": 0.94,
"consensus_level": "STRONG",
"evidence": {
"supporting": [
{
"source": "https://ir.tesla.com/press-release/tesla-q4-2023",
"confidence": 0.98,
"authority_score": 0.95,
"snippet": "Tesla delivered 1.81 million vehicles in 2023..."
}
],
"contradicting": [],
"neutral": []
},
"fact_check_summary": {
"verdict": "TRUE",
"explanation": "Multiple authoritative sources confirm..."
}
},
"request_id": "req_validate_789ghi"
}
๐ Cache Endpointsโ
GET /v1/cache/queryโ
curl -X GET "https://api.usecortex.co/v1/cache/query?q=AI%20developments" \
-H "Authorization: Bearer YOUR_API_KEY"
POST /v1/cache/storeโ
curl -X POST https://api.usecortex.co/v1/cache/store \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"query": "AI developments",
"content": {...},
"ttl": 3600,
"trust_level": "high"
}'
DELETE /v1/cache/clearโ
curl -X DELETE https://api.usecortex.co/v1/cache/clear \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"tags": ["outdated"],
"older_than": "2025-01-07T00:00:00Z"
}'
๐ Monitoring Endpointsโ
GET /v1/usageโ
curl -X GET "https://api.usecortex.co/v1/usage?period=month" \
-H "Authorization: Bearer YOUR_API_KEY"
GET /v1/healthโ
curl -X GET https://api.usecortex.co/v1/health \
-H "Authorization: Bearer YOUR_API_KEY"
GET /v1/auditโ
curl -X GET "https://api.usecortex.co/v1/audit?limit=50" \
-H "Authorization: Bearer YOUR_API_KEY"
๐จ Error Handlingโ
Error Response Formatโ
{
"success": false,
"error": {
"code": "QUERY_TOO_LONG",
"message": "Query exceeds maximum length of 500 characters",
"details": {
"max_length": 500,
"provided_length": 742
},
"suggestion": "Shorten your query to under 500 characters"
},
"request_id": "req_error_123"
}
HTTP Status Codesโ
200- Success400- Bad Request (invalid parameters)401- Unauthorized (invalid API key)403- Forbidden (insufficient permissions)429- Too Many Requests (rate limited)500- Internal Server Error
๐ป Language Examplesโ
Python (requests)โ
import requests
import json
def cortex_search(query, api_key):
url = "https://api.usecortex.co/v1/search"
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
data = {"query": query}
response = requests.post(url, headers=headers, json=data)
if response.status_code == 200:
return response.json()
else:
print(f"Error: {response.status_code}")
print(response.json())
return None
# Usage
result = cortex_search("AI developments", "your_api_key")
if result:
print(result["data"]["summary"])
Node.js (fetch)โ
async function cortexSearch(query, apiKey) {
const response = await fetch('https://api.usecortex.co/v1/search', {
method: 'POST',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ query })
});
if (response.ok) {
const result = await response.json();
return result;
} else {
const error = await response.json();
console.error('Error:', error);
return null;
}
}
// Usage
const result = await cortexSearch('AI developments', 'your_api_key');
if (result) {
console.log(result.data.summary);
}
PHPโ
<?php
function cortex_search($query, $api_key) {
$url = 'https://api.usecortex.co/v1/search';
$data = json_encode(['query' => $query]);
$options = [
'http' => [
'header' => [
"Authorization: Bearer $api_key",
"Content-Type: application/json"
],
'method' => 'POST',
'content' => $data
]
];
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
if ($response === false) {
return null;
}
return json_decode($response, true);
}
// Usage
$result = cortex_search('AI developments', 'your_api_key');
if ($result) {
echo $result['data']['summary'];
}
?>
Rubyโ
require 'net/http'
require 'json'
def cortex_search(query, api_key)
uri = URI('https://api.usecortex.co/v1/search')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Post.new(uri)
request['Authorization'] = "Bearer #{api_key}"
request['Content-Type'] = 'application/json'
request.body = { query: query }.to_json
response = http.request(request)
if response.code == '200'
JSON.parse(response.body)
else
puts "Error: #{response.code}"
puts response.body
nil
end
end
# Usage
result = cortex_search('AI developments', 'your_api_key')
puts result['data']['summary'] if result
Goโ
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
type SearchRequest struct {
Query string `json:"query"`
}
type SearchResponse struct {
Success bool `json:"success"`
Data struct {
Summary string `json:"summary"`
} `json:"data"`
}
func cortexSearch(query, apiKey string) (*SearchResponse, error) {
reqBody := SearchRequest{Query: query}
jsonData, _ := json.Marshal(reqBody)
req, err := http.NewRequest("POST", "https://api.usecortex.co/v1/search", bytes.NewBuffer(jsonData))
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var searchResp SearchResponse
json.Unmarshal(body, &searchResp)
return &searchResp, nil
}
func main() {
result, err := cortexSearch("AI developments", "your_api_key")
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println(result.Data.Summary)
}
Javaโ
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.URI;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
public class CortexAPI {
private static final String BASE_URL = "https://api.usecortex.co/v1";
private final String apiKey;
private final HttpClient client;
private final Gson gson;
public CortexAPI(String apiKey) {
this.apiKey = apiKey;
this.client = HttpClient.newHttpClient();
this.gson = new Gson();
}
public JsonObject search(String query) throws Exception {
JsonObject requestBody = new JsonObject();
requestBody.addProperty("query", query);
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(BASE_URL + "/search"))
.header("Authorization", "Bearer " + apiKey)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(gson.toJson(requestBody)))
.build();
HttpResponse<String> response = client.send(request,
HttpResponse.BodyHandlers.ofString());
if (response.statusCode() == 200) {
return gson.fromJson(response.body(), JsonObject.class);
} else {
throw new RuntimeException("API request failed: " + response.statusCode());
}
}
public static void main(String[] args) throws Exception {
CortexAPI cortex = new CortexAPI("your_api_key");
JsonObject result = cortex.search("AI developments");
System.out.println(result.getAsJsonObject("data")
.get("summary").getAsString());
}
}
C#โ
using System;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
public class CortexAPI
{
private readonly HttpClient httpClient;
private readonly string apiKey;
public CortexAPI(string apiKey)
{
this.apiKey = apiKey;
this.httpClient = new HttpClient();
this.httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
}
public async Task<JsonDocument> SearchAsync(string query)
{
var requestBody = new { query = query };
var json = JsonSerializer.Serialize(requestBody);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await httpClient.PostAsync("https://api.usecortex.co/v1/search", content);
if (response.IsSuccessStatusCode)
{
var responseContent = await response.Content.ReadAsStringAsync();
return JsonDocument.Parse(responseContent);
}
else
{
throw new HttpRequestException($"API request failed: {response.StatusCode}");
}
}
}
// Usage
var cortex = new CortexAPI("your_api_key");
var result = await cortex.SearchAsync("AI developments");
var summary = result.RootElement.GetProperty("data").GetProperty("summary").GetString();
Console.WriteLine(summary);
๐ Batch Processingโ
Parallel Requestsโ
#!/bin/bash
# Function to make API request
make_request() {
local query="$1"
curl -s -X POST https://api.usecortex.co/v1/search \
-H "Authorization: Bearer $API_KEY" \
-H "Content-Type: application/json" \
-d "{\"query\": \"$query\"}" \
> "result_${query// /_}.json"
}
# Parallel processing
queries=("AI developments" "quantum computing" "renewable energy")
for query in "${queries[@]}"; do
make_request "$query" &
done
wait
echo "All requests completed"
Rate Limitingโ
import time
import requests
from functools import wraps
def rate_limit(calls_per_minute=60):
def decorator(func):
last_called = [0.0]
@wraps(func)
def wrapper(*args, **kwargs):
elapsed = time.time() - last_called[0]
left_to_wait = 60.0 / calls_per_minute - elapsed
if left_to_wait > 0:
time.sleep(left_to_wait)
ret = func(*args, **kwargs)
last_called[0] = time.time()
return ret
return wrapper
return decorator
@rate_limit(calls_per_minute=50) # Stay under 60/min limit
def cortex_search(query, api_key):
# Your search implementation
pass
# Process many queries
queries = ["query1", "query2", "query3", ...]
for query in queries:
result = cortex_search(query, "your_api_key")
# Process result
๐งช Testing & Developmentโ
Health Checkโ
# Simple health check
curl -I https://api.usecortex.co/v1/health
# With authentication
curl -H "Authorization: Bearer YOUR_API_KEY" \
https://api.usecortex.co/v1/health
Sandbox Environmentโ
# Use sandbox for testing
curl -X POST https://sandbox.api.usecortex.co/v1/search \
-H "Authorization: Bearer test_key_sandbox" \
-H "Content-Type: application/json" \
-d '{"query": "test query"}'
Debuggingโ
# Verbose output for debugging
curl -v -X POST https://api.usecortex.co/v1/search \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"query": "test"}' \
2>&1 | tee debug.log
Next: CLI Tool โ - Command-line interface for Cortex