Skip to main content

Quickstart Guide

Get up and running with the Posthoot API in just a few minutes. This guide will walk you through creating your first account, authenticating, and making your first API calls.

πŸš€ Step 1: Create Your Account

First, let’s create a new user account:
curl -X POST https://api.posthoot.com/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "email": "your-email@example.com",
    "password": "your-secure-password",
    "first_name": "Your",
    "last_name": "Name"
  }'
const response = await fetch('https://api.posthoot.com/auth/register', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    email: 'your-email@example.com',
    password: 'your-secure-password',
    first_name: 'Your',
    last_name: 'Name'
  })
});

const data = await response.json();
console.log('Access Token:', data.access_token);

πŸ”‘ Step 2: Store Your Tokens

After registration, you’ll receive access and refresh tokens. Store them securely:
// Store tokens securely (not in localStorage)
const tokens = {
  access_token: data.access_token,
  refresh_token: data.refresh_token
};

// Use secure storage method
localStorage.setItem('posthoot_tokens', JSON.stringify(tokens));

πŸ“§ Step 3: Send Your First Email

Now let’s send a test email using the API:
curl -X POST https://api.posthoot.com/email \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "to": "recipient@example.com",
    "subject": "Hello from Posthoot!",
    "html": "<h1>Welcome to Posthoot</h1><p>This is your first email sent via the API.</p>",
    "provider": "CUSTOM",
    "data": []
  }'
const emailResponse = await fetch('https://api.posthoot.com/email', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${tokens.access_token}`,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    to: 'recipient@example.com',
    subject: 'Hello from Posthoot!',
    html: '<h1>Welcome to Posthoot</h1><p>This is your first email sent via the API.</p>',
    provider: 'CUSTOM',
    data: []
  })
});

const emailResult = await emailResponse.json();
console.log('Email sent:', emailResult);

πŸ“Š Step 4: Check Analytics

Let’s check the analytics for your email:
curl -X GET "https://api.posthoot.com/api/v1/analytics/email?emailId=EMAIL_ID" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"
const analyticsResponse = await fetch(
  `https://api.posthoot.com/api/v1/analytics/email?emailId=${emailResult.emailId}`,
  {
    headers: {
      'Authorization': `Bearer ${tokens.access_token}`
    }
  }
);

const analytics = await analyticsResponse.json();
console.log('Email Analytics:', analytics);

πŸ”„ Step 5: Handle Token Refresh

When your access token expires, refresh it:
async function refreshToken() {
  const response = await fetch('https://api.posthoot.com/auth/refresh', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      refresh_token: tokens.refresh_token
    })
  });

  if (response.ok) {
    const newTokens = await response.json();
    tokens.access_token = newTokens.access_token;
    tokens.refresh_token = newTokens.refresh_token;
    
    // Update stored tokens
    localStorage.setItem('posthoot_tokens', JSON.stringify(tokens));
  } else {
    // Redirect to login
    window.location.href = '/login';
  }
}

πŸ› οΈ Complete Example

Here’s a complete working example:
class PosthootAPI {
  constructor() {
    this.baseURL = 'https://api.posthoot.com';
    this.tokens = this.loadTokens();
  }

  loadTokens() {
    const stored = localStorage.getItem('posthoot_tokens');
    return stored ? JSON.parse(stored) : null;
  }

  saveTokens(tokens) {
    this.tokens = tokens;
    localStorage.setItem('posthoot_tokens', JSON.stringify(tokens));
  }

  async makeRequest(endpoint, options = {}) {
    if (!this.tokens?.access_token) {
      throw new Error('No access token available');
    }

    const response = await fetch(`${this.baseURL}${endpoint}`, {
      ...options,
      headers: {
        'Authorization': `Bearer ${this.tokens.access_token}`,
        'Content-Type': 'application/json',
        ...options.headers
      }
    });

    if (response.status === 401) {
      // Token expired, try to refresh
      await this.refreshToken();
      return this.makeRequest(endpoint, options);
    }

    return response;
  }

  async refreshToken() {
    const response = await fetch(`${this.baseURL}/auth/refresh`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ refresh_token: this.tokens.refresh_token })
    });

    if (response.ok) {
      const newTokens = await response.json();
      this.saveTokens(newTokens);
    } else {
      // Redirect to login
      window.location.href = '/login';
    }
  }

  async register(email, password, firstName, lastName) {
    const response = await fetch(`${this.baseURL}/auth/register`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email, password, first_name: firstName, last_name: lastName })
    });

    if (response.ok) {
      const data = await response.json();
      this.saveTokens({
        access_token: data.access_token,
        refresh_token: data.refresh_token
      });
      return data;
    } else {
      throw new Error('Registration failed');
    }
  }

  async sendEmail(to, subject, html) {
    const response = await this.makeRequest('/email', {
      method: 'POST',
      body: JSON.stringify({
        to,
        subject,
        html,
        provider: 'CUSTOM',
        data: []
      })
    });

    return response.json();
  }

  async getAnalytics(emailId) {
    const response = await this.makeRequest(`/api/v1/analytics/email?emailId=${emailId}`);
    return response.json();
  }
}

// Usage
const api = new PosthootAPI();

// Register (if not already registered)
await api.register('your-email@example.com', 'password123', 'Your', 'Name');

// Send email
const emailResult = await api.sendEmail(
  'recipient@example.com',
  'Hello from Posthoot!',
  '<h1>Welcome</h1><p>This is a test email.</p>'
);

// Check analytics
const analytics = await api.getAnalytics(emailResult.emailId);
console.log('Analytics:', analytics);

🐍 Python Example

import requests
import json

class PosthootAPI:
    def __init__(self):
        self.base_url = 'https://api.posthoot.com'
        self.tokens = None
    
    def register(self, email, password, first_name, last_name):
        response = requests.post(
            f'{self.base_url}/auth/register',
            json={
                'email': email,
                'password': password,
                'first_name': first_name,
                'last_name': last_name
            }
        )
        
        if response.status_code == 201:
            data = response.json()
            self.tokens = {
                'access_token': data['access_token'],
                'refresh_token': data['refresh_token']
            }
            return data
        else:
            raise Exception('Registration failed')
    
    def send_email(self, to, subject, html):
        if not self.tokens:
            raise Exception('Not authenticated')
        
        response = requests.post(
            f'{self.base_url}/email',
            headers={'Authorization': f"Bearer {self.tokens['access_token']}"},
            json={
                'to': to,
                'subject': subject,
                'html': html,
                'provider': 'CUSTOM',
                'data': []
            }
        )
        
        return response.json()
    
    def get_analytics(self, email_id):
        if not self.tokens:
            raise Exception('Not authenticated')
        
        response = requests.get(
            f'{self.base_url}/api/v1/analytics/email',
            headers={'Authorization': f"Bearer {self.tokens['access_token']}"},
            params={'emailId': email_id}
        )
        
        return response.json()

# Usage
api = PosthootAPI()

# Register
api.register('your-email@example.com', 'password123', 'Your', 'Name')

# Send email
result = api.send_email(
    'recipient@example.com',
    'Hello from Posthoot!',
    '<h1>Welcome</h1><p>This is a test email.</p>'
)

# Check analytics
analytics = api.get_analytics(result['emailId'])
print('Analytics:', analytics)

🚨 Error Handling

Always handle errors gracefully:
try {
  const result = await api.sendEmail(to, subject, html);
  console.log('Email sent successfully:', result);
} catch (error) {
  if (error.message.includes('unauthorized')) {
    console.error('Authentication failed. Please log in again.');
  } else if (error.message.includes('rate_limit')) {
    console.error('Rate limit exceeded. Please wait before trying again.');
  } else {
    console.error('An error occurred:', error.message);
  }
}

πŸ“š Next Steps

Now that you’ve completed the quickstart:
  1. Explore the API: Check out the API Reference for all available endpoints
  2. Build Features: Create campaigns, manage contacts, and set up automations
  3. Monitor Performance: Use analytics to track email performance
  4. Set Up Webhooks: Get real-time notifications for email events
  5. Scale Up: Implement advanced features like A/B testing and segmentation

πŸ†˜ Need Help?