publishers

Table of Content

Table of Content

Table of Content

endpoints

accessing end points and how to fetch data

Fetch Ads Endpoint

POST /api/fetch-ads

The Fetch Ads endpoint is the primary integration point for publishers. This single endpoint handles all ad requests from your AI and returns contextually relevant advertisements based on the conversation context and keywords.

Publisher ImplementationThis is the only endpoint you need to implement to start monetizing your AI with Mosaic.


Request Parameters

Headers:

Header

Description

Required

mosaic-api-key

Your unique API key

Yes

content-type

Must be application/json

Yes


Request Body:

{
  "conversation": "string",         // Recent conversation or query from the user
  "context_keywords": "string",    // Comma-separated keywords extracted from the conversation
  "user_location": "string",       // Optional: User's location information
  "user_device_info": "string"     // Optional: User's device information
}


Parameter Details

Parameter Details




Parameter

Type

Description

Required

conversation

string

The recent conversation or query from the user. This helps with analytics and future improvements to ad matching.

Yes

context_keywords

string

Comma-separated keywords extracted from the conversation. These are used to match with relevant ad campaigns.

Yes

user_location

string

User's location information (e.g., city, country). Helps with geo-targeted ads.

Optional

user_device_info

string

Information about the user's device or platform.

Optional


Example Request

POST /api/fetch-ads HTTP/1.1
Host: demo.xmosaic.ai
Content-Type: application/json
mosaic-api-key: YOUR_API_KEY

{
  "conversation": "I'm looking for hiking shoes for my trip to Colorado next month",
  "context_keywords": "hiking,shoes,outdoor,travel,Colorado",
  "user_location": "San Francisco,CA",
  "user_device_info": "Chrome on macOS"
}


Response Format

A successful response will contain an array of advertisements that match the provided keywords. In most cases, only one advertisement will be returned.

{
  "advertisements": [
    {
      "campaign_name": "Summer Hiking Collection",
      "campaign_text": "Discover our premium hiking shoes with 20% off",
      "campaign_image": "https://example.com/images/hiking-shoes.jpg",
      "campaign_markdown": "**Discover our premium hiking shoes with 20% off** [![Summer Hiking Collection](https://example.com/images/hiking-shoes.jpg)](https://demo.xmosaic.ai/api/campaign_click?campaign_id=123&model_id=456&targetLink=https%3A%2F%2Fexample.com%2Fhiking-shoes) **♦ Powered by Mosaic**",
      "campaign_link": "https://demo.xmosaic.ai/api/campaign_click?campaign_id=123&model_id=456&targetLink=https%3A%2F%2Fexample.com%2Fhiking-shoes",
      "bid_per_click": 0.35
    }
  ]
}


Response Fields

Field

Type

Description

campaign_name

string

Name of the ad campaign

campaign_text

string

Text content of the advertisement

campaign_image

string

URL of the image to display (if available)

campaign_markdown

string

Ready-to-use markdown that combines the ad text, image, and tracking link

campaign_link

string

Tracking URL that should be used for any clicks on the ad

bid_per_click

number

The bid amount per click for the ad campaign

Implementation RecommendationFor most publishers, the simplest implementation is to use the campaign_markdown field directly in your AI model's response. This field contains the complete ad with proper tracking links already formatted in markdown.


Implementation Guide

Your integration should extract and send relevant keywords from each conversation to the Mosaic API.\


1.Call the API

Once you have the user context or keywords, make a request to the Fetch Ads endpoint:

async function fetchAd(conversation) {
  // Get user context and keywords (if available)
  const keywords = getUserContextAndKeywords(conversation);

  try {
    const response = await fetch('https://demo.xmosaic.ai/api/fetch-ads', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'mosaic-api-key': process.env.MOSAIC_API_KEY
      },
      body: JSON.stringify({
        conversation,
        context_keywords: keywords,
        user_location: 'United States', // Optional
        user_device_info: 'AI Client' // Optional
      })
    });

    if (!response.ok) {
      throw new Error(`API error: ${response.status}`);
    }

    const data = await response.json();
    return data.advertisements[0]; // Get the first advertisement
  } catch (error) {
    console.error('Error fetching ad:', error);
    return null; // Return null if there's an error
  }
}


2. Display the Ad

Finally, display the ad to the user:

async function getResponseWithAd(userMessage) {
  // Generate your AI response
  const aiResponse = await generateAIResponse(userMessage);

  // Fetch a relevant ad
  const ad = await fetchAd(userMessage);

  // If an ad was found, append it to the response
  if (ad) {
    return `${aiResponse}\n\n${ad.campaign_markdown}`;
  }

  // Otherwise, just return the AI response
  return aiResponse;
}


How Ad Matching Works

The /api/fetch-ads endpoint analyzes the conversation context and keywords, matches them against active campaigns, scores for relevance and bid, and returns the most suitable ad with tracking.


Automatic Tracking

Mosaic handles all tracking automatically:

  • Impressions: Recorded when you call the /api/fetch-ads endpoint

  • Clicks: Tracked when users click on the ad using the provided campaign_link

  • Earnings: Calculated based on the campaign's bid amount and your revenue share


Campaign Click Tracking

GET/api/campaign_click

This endpoint is used internally by the tracking links generated in the /api/fetch-ads response. You do not need to call this endpoint directly - it's automatically used when a user clicks on an ad.

Publisher NoteThis endpoint is documented for informational purposes only. The tracking links are automatically generated and included in the campaign_markdown and campaign_link fields of the /api/fetch-ads response.


Error Handling

When implementing the Fetch Ads endpoint, be sure to handle these common error scenarios:

Status Code

Error

Description

Recommendation

400

Bad Request

Missing required parameters

Check that you're including both conversation and context_keywords

404

Not Found

Invalid API key or no matching ads

Verify your API key and try different keywords

500

Server Error

Internal server error

Implement retry logic with exponential backoff

Always implement graceful fallbacks in case no ads are available or the API request fails.