TheNews API Documentation
Welcome to TheNews API documentation. TheNews is a powerful email marketing platform that allows you to manage subscribers, create and send newsletters, and track analytics.
Overview
The API is organized around REST. It uses resource-oriented URLs, JSON-encoded request/response bodies, and standard HTTP verbs.
Before adding subscribers using POST /api/subscribe
, you must first create a newsletter category from the TheNews Dashboard. This category determines what type of newsletter the user is subscribing to.
Base URL
https://thenews.africa/api/subscribe
Available Endpoints
Endpoint | Description |
---|---|
POST /api/subscribe | Add a new subscriber to your list |
GET /api/subscribe | List all subscribers |
Coming Soon
We're working on expanding our API with exciting new features and endpoints!
Analytics API
Track performance metrics for your newsletters
Webhooks
Real-time event notifications
Templates API
Create and manage newsletter templates
API Versioning
The TheNews API is versioned to ensure backward compatibility. The current version is v0.5. When we make breaking changes, we'll release a new version and provide migration guides.
Authentication
The TheNews API uses API keys to authenticate requests. You can view and manage your API keys in the TheNews Dashboard.
Your API keys carry many privileges, so be sure to keep them secure! Do not share your API keys in publicly accessible areas such as GitHub, client-side code, etc.
Authentication Methods
Authentication to the API is performed via HTTP Bearer Auth. Provide your API key as the bearer token value.
HTTP Bearer Auth
All API requests must include your API key in the Authorization header:
Authorization: Bearer your_api_key_here
API Key Security
- Never expose your API key in client-side JavaScript
- Use environment variables to store your API key in your applications
- For browser-based applications, make API calls from your server, not directly from the browser
- Implement proper CORS policies on your server
- Rotate your API keys periodically
Authentication Example
// Authentication with API Key
const apiKey = 'your_api_key_here';
fetch('https://api.thenews.sixthgrid.com/v1/api/subscribers', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
},
body: JSON.stringify({
email: 'subscriber@example.com',
name: 'John Doe'
})
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Quick Start
This guide will help you get started with the TheNews API quickly. We'll walk through the basic steps to add a new subscriber to your newsletter.
Prerequisites
- Create a TheNews account at https://thenews.africa/sign-up
- Obtain your API key from the dashboard.
Step 1: Set Up Your Environment
Make sure you have your API key ready. You'll need to include it in all requests.
Step 2: Add a Subscriber
Use the /api/subscribe
endpoint to add a user to your list.
Every subscriber must be linked to a newsletter category using a valid categoryId
. Create and manage categories via your TheNews Dashboard.
// Quick start example
const apiKey = 'your_api_key_here';
// 1. Add a new subscriber
async function addSubscriber() {
try {
const response = await fetch('https://api.thenews.sixthgrid.com/v1/api/subscribe', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
},
body: JSON.stringify({
email: 'new.subscriber@example.com',
name: 'Jane Smith',
categoryId: 'your_category_id_here', // ✅ Required: specify newsletter category
metadata: {
campaign: "thenews website landing page",
pageUrl: '',
formId: "TheNews website general sub page",
},
})
});
const data = await response.json();
if (response.ok) {
console.log('Subscriber added successfully:', data);
} else {
console.error('Error adding subscriber:', data);
}
} catch (error) {
console.error('Network error:', error);
}
}
addSubscriber();
Step 3: Verify the Response
If successful, you should get a response like this:
{
"id": "sub_1234567890",
"email": "new.subscriber@example.com",
"name": "Jane Smith",
"categoryId": "your_category_id_here",
"preferences": {
"newsletter_frequency": "weekly",
"topics": ["technology", "marketing"]
},
"created_at": "2023-05-01T12:00:00Z"
}
API Base URL
https://thenews.africa/api/
Rate Limits
Learn about the rate limits for TheNews API and how to handle them.
Overview
To ensure fair usage and maintain service stability, TheNews API implements rate limiting. Rate limits are applied on a per-API key basis.
Rate Limit Tiers
Rate limits vary based on your subscription plan:
Plan | Requests per Minute | Requests per Day |
---|---|---|
Free | 60 | 10,000 |
Basic | 300 | 50,000 |
Pro | 1,000 | 200,000 |
Enterprise | Custom | Custom |
Rate Limit Headers
Each API response includes headers that provide information about your current rate limit status:
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 59
X-RateLimit-Reset: 1620000000
- X-RateLimit-Limit: The maximum number of requests you can make per minute
- X-RateLimit-Remaining: The number of requests remaining in the current rate limit window
- X-RateLimit-Reset: The time at which the current rate limit window resets in Unix time
Rate Limit Exceeded
If you exceed your rate limit, you'll receive a 429 Too Many Requests response:
1{2 "success": false,3 "error": {4 "code": "rate_limit_exceeded",5 "message": "Rate limit exceeded. Please try again later",6 "status": 429,7 "retry_after": 308 }9}
The retry_after field indicates the number of seconds to wait before making another request.
Best Practices
Here are some best practices for working with rate limits:
- Monitor the rate limit headers in API responses
- Implement exponential backoff for retries
- Cache responses when possible to reduce the number of API calls
- Batch requests when possible
- Upgrade your plan if you consistently hit rate limits
Example: Handling Rate Limits
Here's an example of how to handle rate limits in your code:
1async function makeApiRequest(url, options, retries = 3) {2 try {3 const response = await fetch(url, options);4 5 // Check if rate limited6 if (response.status === 429) {7 const data = await response.json();8 const retryAfter = data.error.retry_after || 60; // Default to 60 seconds9 10 console.log(`Rate limited. Retrying after ${retryAfter} seconds`);11 12 if (retries > 0) {13 // Wait for the specified time14 await new Promise(resolve => setTimeout(resolve, retryAfter * 1000));15 16 // Retry the request with one less retry17 return makeApiRequest(url, options, retries - 1);18 } else {19 throw new Error('Maximum retries reached');20 }21 }22 23 return response;24 } catch (error) {25 console.error('API request failed:', error);26 throw error;27 }28}2930// Example usage31makeApiRequest('https://api.thenews.africca/api/subscribe', {32 method: 'POST',33 headers: {34 'Content-Type': 'application/json',35 'Authorization': `Bearer ${API_KEY}`36 },37 body: JSON.stringify({38 email: 'subscriber@example.com',39 name: 'John Doe'40 })41})42.then(response => response.json())43.then(data => console.log(data))44.catch(error => console.error('Error:', error));
Error Codes
Learn about the error codes returned by TheNews API and how to handle them.
Error Response Format
When an error occurs, the API will return a JSON object with an error message and code:
1{2 "success": false,3 "error": {4 "code": "error_code",5 "message": "A human-readable error message",6 "status": 400,7 "details": { /* Additional error details if available */ }8 }9}
HTTP Status Codes
The API uses standard HTTP status codes to indicate the success or failure of a request:
Status Code | Description |
---|---|
200 - OK | The request was successful |
201 - Created | The resource was successfully created |
400 - Bad Request | The request was invalid or missing required parameters |
401 - Unauthorized | Authentication failed or was not provided |
403 - Forbidden | The request was valid but the server refused to respond |
404 - Not Found | The requested resource was not found |
409 - Conflict | The request conflicts with the current state of the server |
429 - Too Many Requests | Rate limit exceeded |
500 - Server Error | An error occurred on the server |
Error Codes
The API uses the following error codes to provide more specific information about what went wrong:
Error Code | Description | HTTP Status |
---|---|---|
invalid_request | The request was malformed or missing required parameters | 400 |
invalid_email | The provided email address is invalid | 400 |
newsletter_not_found | The specified newsletter does not exist | 404 |
subscriber_exists | The subscriber already exists in the newsletter | 409 |
unauthorized | Invalid or missing API key | 401 |
forbidden | The API key does not have permission to perform this action | 403 |
rate_limit_exceeded | Rate limit exceeded | 429 |
server_error | An error occurred on the server | 500 |
Error Examples
Here are some examples of error responses you might encounter:
Invalid Email
1{2 "success": false,3 "error": {4 "code": "invalid_email",5 "message": "The provided email address is invalid",6 "status": 4007 }8}
Newsletter Not Found
1{2 "success": false,3 "error": {4 "code": "newsletter_not_found",5 "message": "The specified newsletter does not exist",6 "status": 4047 }8}
Rate Limit Exceeded
1{2 "success": false,3 "error": {4 "code": "rate_limit_exceeded",5 "message": "Rate limit exceeded. Please try again later",6 "status": 429,7 "retry_after": 308 }9}
Handling Errors
Here's an example of how to handle errors in your code:
1fetch('https://api.thenews.africa/api/subscribe', {2 method: 'POST',3 headers: {4 'Content-Type': 'application/json',5 'Authorization': `Bearer ${API_KEY}`6 },7 body: JSON.stringify({8 email: 'subscriber@example.com',9 name: 'John Doe'10 })11})12.then(response => response.json())13.then(data => {14 if (!data.success) {15 // Handle specific error codes16 switch (data.error.code) {17 case 'invalid_email':18 console.error('Please provide a valid email address');19 break;20 case 'newsletter_not_found':21 console.error('The newsletter does not exist');22 break;23 case 'subscriber_exists':24 console.error('This email is already subscribed');25 break;26 case 'rate_limit_exceeded':27 console.error(`Too many requests. Try again in ${data.error.retry_after} seconds`);28 break;29 default:30 console.error(`Error: ${data.error.message}`);31 }32 return;33 }34 35 // Handle success36 console.log('Subscription successful!', data);37})38.catch(error => {39 // Handle network errors40 console.error('Network error:', error);41});
Best Practices
Learn how to use TheNews API effectively and efficiently.
Authentication
- Always use Bearer token authentication for production applications
- Store your API key securely and never expose it in client-side code
- Use environment variables to store your API key
- Rotate your API key regularly
- Use different API keys for development and production
Rate Limiting
- Monitor the rate limit headers in API responses
- Implement exponential backoff for retries
- Cache responses when possible to reduce the number of API calls
- Batch requests when possible
- Upgrade your plan if you consistently hit rate limits
Error Handling
- Always check the
success
field in API responses - Handle specific error codes appropriately
- Implement proper logging for API errors
- Display user-friendly error messages to your users
- Implement retry logic for transient errors
Here's an example of good error handling:
1function handleApiError(error) {2 // Log the error for debugging3 console.error('API Error:', error);4 5 // Handle specific error codes6 switch (error.code) {7 case 'invalid_email':8 return 'Please provide a valid email address';9 case 'newsletter_not_found':10 return 'The newsletter category does not exist';11 case 'subscriber_exists':12 return 'This email is already subscribed';13 case 'rate_limit_exceeded':14 return `Too many requests. Try again in ${error.retry_after} seconds`;15 default:16 return 'An error occurred. Please try again later';17 }18}1920// Example usage21fetch('https://api.thenews.africa/api/subscribe', {22 method: 'POST',23 headers: {24 'Content-Type': 'application/json',25 'Authorization': `Bearer ${API_KEY}`26 },27 body: JSON.stringify({28 email: 'subscriber@example.com',29 newsletter_id: 'news_1a2b3c4d5e6f'30 })31})32.then(response => response.json())33.then(data => {34 if (!data.success) {35 const errorMessage = handleApiError(data.error);36 showErrorToUser(errorMessage);37 return;38 }39 40 // Handle success41 showSuccessToUser('Subscription successful!');42})43.catch(error => {44 // Handle network errors45 showErrorToUser('Network error. Please check your connection');46});
Performance Optimization
- Cache API responses when appropriate
- Use pagination for large data sets
- Only request the data you need
- Batch operations when possible
- Implement request throttling to avoid rate limits
Here's an example of caching API responses:
1// Simple in-memory cache2const cache = new Map();3const CACHE_TTL = 60 * 1000; // 1 minute in milliseconds45async function fetchWithCache(url, options) {6 const cacheKey = `${url}-${JSON.stringify(options.body || {})}`;7 8 // Check if we have a cached response9 if (cache.has(cacheKey)) {10 const { data, timestamp } = cache.get(cacheKey);11 12 // Check if the cache is still valid13 if (Date.now() - timestamp < CACHE_TTL) {14 console.log('Using cached response');15 return data;16 }17 18 // Cache expired, remove it19 cache.delete(cacheKey);20 }21 22 // Make the API request23 const response = await fetch(url, options);24 const data = await response.json();25 26 // Cache the response if it was successful27 if (data.success) {28 cache.set(cacheKey, {29 data,30 timestamp: Date.now()31 });32 }33 34 return data;35}3637// Example usage38fetchWithCache('https://api.thenews.africa/api/newsletters', {39 method: 'GET',40 headers: {41 'Content-Type': 'application/json',42 'Authorization': `Bearer ${API_KEY}`43 }44})45.then(data => {46 if (data.success) {47 displayNewsletters(data.data);48 } else {49 handleApiError(data.error);50 }51})52.catch(error => {53 console.error('Network error:', error);54});
Security
- Always use HTTPS for API requests
- Validate and sanitize user input before sending it to the API
- Implement proper authentication and authorization in your application
- Keep your API keys secure
- Follow the principle of least privilege
Testing
- Use the free plan for sandbox testing
- Write automated tests for your API integration
- Test error handling and edge cases
- Use mock responses for testing
- Test rate limiting behavior
GET /subscribe
Retrieve a paginated list of all subscribers linked to your newsletter. You can filter results using query parameters.
Request
GET https://thenews.africa/api/subscribe?page=1&limit=20&status=Subscribed
Query Parameters
Parameter | Type | Description |
---|---|---|
page | integer | Page number (default: 1) |
limit | integer | Number of records per page (default: 20, max: 100) |
status | string | Filter by subscriber status (e.g. Subscribed, Unsubscribed) |
search | string | Search by email or source |
Response
Returns a list of subscribers with pagination info.
Example Response
{
"success": true,
"data": [
{
"_id": "sub_123456789",
"email": "john@example.com",
"status": "Subscribed",
"source": "API - Website Form",
"createdAt": "2025-05-01T12:00:00Z",
"metadata": {
"campaign": "spring-launch",
"pageUrl": "https://example.com/subscribe",
"formId": "form-001"
}
},
{
"_id": "sub_987654321",
"email": "jane@example.com",
"status": "Subscribed",
"source": "API - Referral",
"createdAt": "2025-05-02T09:30:00Z",
"metadata": {
"campaign": null,
"pageUrl": "https://another.com",
"formId": null
}
}
],
"pagination": {
"page": 1,
"limit": 20,
"total": 42,
"pages": 3
}
}
Error Codes
Code | Description |
---|---|
401 | Unauthorized – Invalid API key |
403 | Forbidden – No active subscription |
429 | Too Many Requests – Rate limit exceeded |
POST /subscribe
Add a new subscriber to your newsletter list. If the email already exists, their information will be updated.
Request
POST https://thenews.africa/api/subscribe
Request Body
Parameter | Type | Required | Description |
---|---|---|---|
string | Yes | Email address of the subscriber | |
categoryId | string | Yes | ID of the category to associate the subscriber with and to know the category of the newsletter |
source | string | Yes | Describes the source of subscription (e.g., "website") |
metadata | object | No | Additional information such as campaign, pageUrl, or formId |
Example Request
{
"email": "john@example.com",
"categoryId": "64f10dd3a9b23c5aebf1e123",
"source": "Website Form",
"metadata": {
"campaign": "spring-launch",
"pageUrl": "https://example.com/subscribe",
"formId": "signup-form-001"
}
}
Response
Returns the newly created or updated subscriber object.
Example Response
{
"success": true,
"data": {
"_id": "sub_123456789",
"email": "john@example.com",
"newsLetterOwnerId": "user_123",
"category": "64f10dd3a9b23c5aebf1e123",
"source": "API - Website Form",
"status": "Subscribed",
"metadata": {
"campaign": "spring-launch",
"pageUrl": "https://example.com/subscribe",
"formId": "signup-form-001"
},
"createdAt": "2025-05-20T12:00:00Z",
"updatedAt": "2025-05-20T12:00:00Z"
}
}
Error Codes
Code | Description |
---|---|
400 | Bad Request – Missing or invalid fields |
401 | Unauthorized – Invalid or missing API key |
403 | Forbidden – No active subscription for API key |
429 | Too Many Requests – Rate limit exceeded - Usage limit exceeded |