# Revenue API

## **Overview**

The **RevenueMetrics API** allows you to retrieve performance data for websites and ad units over a specific date range. This data includes key metrics such as revenue, impressions, clicks, and other performance indicators, providing actionable insights for optimizing ad performance.

***

## **API** Detail&#x73;**：**

### &#x20; **API Endpoint**

* <https://public-api.myappfree.com/graphql/index.html>

### &#x20;**Authentication**

Access to the API requires an API key. This key can be obtained in the [Universal Developer Portal](https://dashboard.maf.ad). Once obtained, the key must be included in the HTTP request header under the field `x-api-key`.&#x20;

* Auth Type:  API Key
* Header Name:  x-api-key
* Usage Example:

```graphql
x-api-key: YOUR_API_KEY
```

Replace the string **`YOUR_API_KEY`** in the code with your actual API key

### **Request Parameters**

| Parameter | Type   | Required | Description                              |
| --------- | ------ | -------- | ---------------------------------------- |
| dateFrom  | string | ✅ Yes    | Start date (format: YYYY-MM-DD HH:MM:SS) |
| dateTo    | string | ✅ Yes    | End date (format: YYYY-MM-DD HH:MM:SS)   |

<br>

## **GraphQL Query Example**

The following GraphQL query retrieves performance metrics for websites and ad units within a specified date range.&#x20;

**Request Example:**

```graphql
query RevenueMetrics {
  revenueMetrics(
    where: {
      dateFrom: "2024-12-31 00:00:00",
      dateTo: "2024-12-31 23:59:59"
    }
  ) {
    total
    items {
      siteId
      siteName
      adunitId
      adunitName
      impressions
      clicks
      revenue
      ecpm
      arpdau
      dau
    }
  }
}
```

\
Below are practical examples of how to send requests to the Revenue Metrics API using various popular programming languages, such as Node.js, Python, and C#. These examples demonstrate how to structure your requests, authenticate using an API key, and handle responses effectively.

{% tabs %}
{% tab title="Node.js" %}

```javascript
const fetch = require('node-fetch');

async function FetchRevenueMetrics(apiKey, dateFrom, dateTo) {
  const url = "https://public-api.myappfree.com/graphql/index.html";
  const headers = {
    "x-api-key": apiKey,
    "Content-Type": "application/json"
  };
  const query = {
    query: `
    query RevenueMetrics($fromDate: String!, $toDate: String!) {
      revenueMetrics(where: { dateFrom: $fromDate, dateTo: $toDate }) {
        total
        items {
          siteId
          siteName
          adunitId
          adunitName
          impressions
          clicks
          revenue
          ecpm
          arpdau
          dau
        }
      }
    }`,
    variables: {
      fromDate: dateFrom,
      toDate: dateTo
    }
  };

  const response = await fetch(url, {
    method: "POST",
    headers: headers,
    body: JSON.stringify(query)
  });

  if (response.ok) {
    const data = await response.json();
    return data;
  } else {
    throw new Error(`Query failed with status ${response.status}: ${await response.text()}`);
  }
}

// Usage example
const apiKey = "YOUR_API_KEY";
const dateFrom = "2025-01-10 00:00:00";
const dateTo = "2025-01-10 10:00:00";

FetchRevenueMetrics(apiKey, dateFrom, dateTo)
  .then(data => {
    console.log("Revenue Metrics:");
    console.log(JSON.stringify(data, null, 2)); // Pretty print the response with indentation
  })
  .catch(err => console.error("Error:", err));

```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import json

def FetchRevenueMetrics(api_key, date_from, date_to):
    url = "https://public-api.myappfree.com/graphql/index.html"
    headers = {
        "x-api-key": api_key,
        "Content-Type": "application/json"
    }
    query = {
        "query": """
        query RevenueMetrics($fromDate: String!, $toDate: String!) {
            revenueMetrics(where: { dateFrom: $fromDate, dateTo: $toDate }) {
                total
                items {
                    siteId
                    siteName
                    adunitId
                    adunitName
                    impressions
                    clicks
                    revenue
                    ecpm
                    arpdau
                    dau
                }
            }
        }
        """,
        "variables": {
            "fromDate": date_from,
            "toDate": date_to
        }
    }

    response = requests.post(url, json=query, headers=headers)

    if response.status_code == 200:
        return response.json()
    else:
        raise Exception(f"Query failed with status code {response.status_code}: {response.text}")

# Usage example
api_key = "YOUR_API_KEY"
date_from = "2025-01-10 00:00:00"
date_to = "2025-01-10 10:00:00"

try:
    data = FetchRevenueMetrics(api_key, date_from, date_to)
    print("Revenue Metrics:")
    print(json.dumps(data, indent=2))  # Pretty print the response
except Exception as e:
    print("Error:", e)
```

{% endtab %}

{% tab title="C#" %}

```csharp
using System;
using RestSharp;
using Newtonsoft.Json;

class Program
{
    static dynamic FetchRevenueMetrics(string apiKey, string dateFrom, string dateTo)
    {
        var client = new RestClient("https://public-api.myappfree.com/graphql/index.html");
        var request = new RestRequest(Method.POST);
        request.AddHeader("Content-Type", "application/json");
        request.AddHeader("x-api-key", apiKey);

        var query = new
        {
            query = @"
            query RevenueMetrics($fromDate: String!, $toDate: String!) {
                revenueMetrics(where: { dateFrom: $fromDate, dateTo: $toDate }) {
                    total
                    items {
                        siteId
                        siteName
                        adunitId
                        adunitName
                        impressions
                        clicks
                        revenue
                        ecpm
                        arpdau
                        dau
                    }
                }
            }",
            variables = new
            {
                fromDate = dateFrom,
                toDate = dateTo
            }
        };

        string jsonBody = JsonConvert.SerializeObject(query);
        request.AddParameter("application/json", jsonBody, ParameterType.RequestBody);

        IRestResponse response = client.Execute(request);

        if (response.IsSuccessful)
        {
            return JsonConvert.DeserializeObject(response.Content);
        }
        else
        {
            throw new Exception($"Query failed with status code {response.StatusCode}: {response.Content}");
        }
    }
    
    // Usage example
    static void Main(string[] args)
    {
        string apiKey = "YOUR_API_KEY";
        string dateFrom = "2025-01-10 00:00:00";
        string dateTo = "2025-01-10 10:00:00";

        try
        {
            var data = FetchRevenueMetrics(apiKey, dateFrom, dateTo);
            Console.WriteLine("Revenue Metrics:");
            Console.WriteLine(JsonConvert.SerializeObject(data, Formatting.Indented)); // Pretty print the response
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }
    
    
}

```

{% endtab %}

{% tab title="Shell" %}

<pre class="language-sh"><code class="lang-sh"><strong>
</strong><strong>#!/bin/bash
</strong>
# Define API key, dates, and endpoint
API_KEY="YOUR_API_KEY"
DATE_FROM="2025-01-10 00:00:00"
DATE_TO="2025-01-10 10:00:00"
URL="https://public-api.myappfree.com/graphql/index.html"

# Define GraphQL query
QUERY=$(cat &#x3C;&#x3C;EOF
{
  "query": "query RevenueMetrics(\$fromDate: String!, \$toDate: String!) {
    revenueMetrics(where: { dateFrom: \$fromDate, dateTo: \$toDate }) {
      total
      items {
        siteId
        siteName
        adunitId
        adunitName
        impressions
        clicks
        revenue
        ecpm
        arpdau
        dau
      }
    }
  }",
  "variables": {
    "fromDate": "$DATE_FROM",
    "toDate": "$DATE_TO"
  }
}
EOF
)

# Send POST request using curl
RESPONSE=$(curl --silent --show-error --fail --request POST \
  --url "$URL" \
  --header "Content-Type: application/json" \
  --header "x-api-key: $API_KEY" \
  --data "$QUERY")

# Check if the response is successful
if [ $? -eq 0 ]; then
  echo "Revenue Metrics:"
  echo "$RESPONSE" | jq .  # Pretty print JSON using jq
else
  echo "Error: Failed to fetch revenue metrics" >&#x26;2
  exit 1
fi

</code></pre>

{% endtab %}
{% endtabs %}

## **Response Example**

**Successful Response (200 OK)**

If your request is successful, the response will follow this JSON structure:

```graphql
{
  "data": {
    "revenueMetrics": {
      "total": 1,
      "items": [
        {
          "siteId": 123,
          "siteName": "Example Site",
          "adunitId": 456,
          "adunitName": "Top Banner",
          "impressions": 10000,
          "clicks": 500,
          "revenue": 1500.50,
          "ecpm": 15.05,
          "arpdau": 3.25,
          "dau": 500
        }
      ]
    }
  }
}
```

## **Key Response Fields**

Below is a table summarizing key fields returned in the API responses. This will help you interpret and use the data effectively in your application.

| Field       | Type    | Description                           |
| ----------- | ------- | ------------------------------------- |
| total       | number  | Total item returned                   |
| siteId      | integer | Unique identifier for the site        |
| siteName    | string  | Name of the site                      |
| adunitId    | integer | Unique identifier for the ad unit     |
| adunitName  | string  | Name of the ad unit                   |
| impressions | integer | Total ad impressions                  |
| clicks      | integer | Total ad clicks                       |
| revenue     | number  | Total revenue generated               |
| ecpm        | number  | Effective cost per mille              |
| arpdau      | number  | Average revenue per daily active user |
| dau         | integer | Daily active users                    |

***

## **Error Response Examples**

When interacting with the API, you may encounter errors if the request is not properly formatted or authorized. This section highlights common issues, their causes, and how to resolve them. Below are examples of typical error responses and what they indicate.

**1. Invalid Date Range**:

```graphql
{
  "errors": [
    {
      "message": "Property DateFrom must be earlier than or equal to DateTo. Please correct the date range.",
      "locations": [
        {
          "line": 2,
          "column": 5
        }
      ],
      "path": [
        "revenueMetrics"
      ]
    }
  ],
  "data": {
    "revenueMetrics": null
  }
}
```

**2. Syntax or Time Range Error:**

```graphql
{
    "errors": [
        {
            "message": "Property DateTo should be in the format yyyy-MM-dd HH:mm:ss. Please correct it.",
            "locations": [
                {
                    "line": 2,
                    "column": 5
                }
            ],
            "path": [
                "revenueMetrics"
            ]
        }
    ],
    "data": {
        "revenueMetrics": null
    }
}
```

**3. Invalid API Key:**

```graphql
{
    "errors": [
        {
            "message": "The current user is not authorized to access this resource.",
            "locations": [
                {
                    "line": 2,
                    "column": 5
                }
            ],
            "path": [
                "revenueMetrics"
            ],
            "extensions": {
                "code": "AUTH_NOT_AUTHORIZED"
            }
        }
    ],
    "data": {
        "revenueMetrics": null
    }
}
```
