# Get Automation Stats by ID

## API Overview

As a Marketing Campaigns customer, you have access to rich statistics about your Single Sends and Automations. The Marketing Campaigns Statistics API allows you to retrieve these statistics programmatically. for detailed information about the statistics available, see the [**Marketing Campaigns Stats Overview**](/docs/sendgrid/ui/analytics-and-reporting/marketing-campaigns-stats-overview).

> \[!NOTE]
>
> These endpoints provide stats for Marketing Campaigns only. For stats related to event tracking, please see the [**Stats API**](/docs/sendgrid/api-reference/stats).

## Operation overview

```json
{"path":"https://api.sendgrid.com/v3/marketing/stats/automations/{id}","method":"get","servers":[{"url":"https://api.sendgrid.com","description":"The Twilio SendGrid v3 API"}]}
```

**This endpoint allows you to retrieve stats for a single Automation using its ID.**

Multiple Automation IDs can be retrieved using the "Get All Automation Stats" endpoint. Once you have an ID, this endpoint will return detailed stats for the single automation specified.

You may constrain the stats returned using the `start_date` and `end_date` query string parameters. You can also use the `group_by` and `aggregated_by` query string parameters to further refine the stats returned.

## Operation details

### Authentication

API Key

### Headers

```json
[{"in":"header","name":"Authorization","required":true,"default":"Bearer <<YOUR_API_KEY_HERE>>","schema":{"type":"string"}}]
```

### Path parameters

```json
[{"name":"id","in":"path","description":"The ID of the Automation for which you want to retrieve statistics. ","required":true,"schema":{"type":"string"}}]
```

### Query string

```json
[{"name":"group_by","in":"query","description":"Automations can have multiple steps. Including `step_id` as a `group_by` metric allows further granularity of stats.","style":"form","explode":false,"schema":{"type":"array","items":{"type":"string","enum":["step_id"],"refName":"Items","modelName":"Items"}},"refName":"#/components/parameters/AutomationQueryParamsGroupBy","modelName":"__components_parameters_AutomationQueryParamsGroupBy"},{"name":"step_ids","in":"query","description":"Comma-separated list of `step_ids` that you want the link stats for.","style":"form","explode":false,"schema":{"type":"array","items":{"type":"string","format":"uuid"},"uniqueItems":true},"refName":"#/components/parameters/AutomationQueryParamsStepId","modelName":"__components_parameters_AutomationQueryParamsStepId"},{"name":"aggregated_by","in":"query","description":"Dictates how the stats are time-sliced. Currently, `\"total\"` and `\"day\"` are supported.","schema":{"type":"string","default":"total","enum":["day","total"],"refName":"AggregatedBy","modelName":"AggregatedBy"},"refName":"#/components/parameters/AggregatedByBaseProps","modelName":"__components_parameters_AggregatedByBaseProps"},{"name":"start_date","in":"query","description":"Format: `YYYY-MM-DD`. If this parameter is included, the stats' start date is included in the search.","schema":{"type":"string","format":"date","default":"2021-01-01"},"refName":"#/components/parameters/StartDateBaseProps","modelName":"__components_parameters_StartDateBaseProps"},{"name":"end_date","in":"query","description":"Format: `YYYY-MM-DD`.If this parameter is included, the stats' end date is included in the search.","schema":{"type":"string","format":"date","default":"2021-12-31"},"refName":"#/components/parameters/EndDateBaseProps","modelName":"__components_parameters_EndDateBaseProps"},{"name":"timezone","in":"query","description":"[IANA Area/Region](https://en.wikipedia.org/wiki/Tz_database#Names_of_timezones) string representing the timezone in which the stats are to be presented, e.g., \"America/Chicago\".","schema":{"type":"string","default":"UTC"},"refName":"#/components/parameters/TimezoneBaseProps","modelName":"__components_parameters_TimezoneBaseProps"},{"name":"page_size","in":"query","description":"The number of elements you want returned on each page.","schema":{"type":"integer","minimum":1,"maximum":50,"default":25},"refName":"#/components/parameters/PaginationPageSize","modelName":"__components_parameters_PaginationPageSize"},{"name":"page_token","in":"query","description":"The stats endpoints are paginated. To get the next page, call the passed `_metadata.next` URL. If `_metadata.prev` doesn't exist, you're at the first page. Similarly, if `_metadata.next` is not present, you're at the last page.","schema":{"type":"string"},"refName":"#/components/parameters/PaginationPageToken","modelName":"__components_parameters_PaginationPageToken"}]
```

### Responses

```json
[{"responseCode":"200","schema":{"description":"","content":{"application/json":{"schema":{"title":"AutomationsResponse","type":"object","required":["results"],"refName":"AutomationsResponse","modelName":"AutomationsResponse","properties":{"results":{"type":"array","items":{"type":"object","required":["id","aggregation","step_id"],"properties":{"id":{"type":"string","description":"This is the ID of the Automation you are requesting stats for.","format":"uuid"},"aggregation":{"type":"string","description":"This describes the time unit to which the stat is rolled up. It is based on the `aggregated_by` parameter included in the request. It can be \"total\" or the date (in YYYY-MM-DD format) the stats are for.","default":"total"},"step_id":{"type":"string","description":"This is the ID of the step if the stats were requested to be grouped by `step_id`.","default":"all"},"stats":{"title":"metrics","type":"object","required":["bounce_drops","bounces","clicks","delivered","invalid_emails","opens","requests","spam_report_drops","spam_reports","unique_clicks","unique_opens","unsubscribes"],"refName":"Metrics","modelName":"Metrics","properties":{"bounce_drops":{"type":"integer"},"bounces":{"type":"integer"},"clicks":{"type":"integer"},"delivered":{"type":"integer"},"invalid_emails":{"type":"integer"},"opens":{"type":"integer"},"requests":{"type":"integer"},"spam_report_drops":{"type":"integer"},"spam_reports":{"type":"integer"},"unique_clicks":{"type":"integer"},"unique_opens":{"type":"integer"},"unsubscribes":{"type":"integer"}}}}}},"_metadata":{"title":"metadata","type":"object","refName":"Metadata","modelName":"Metadata","properties":{"prev":{"type":"string","format":"uri","description":"The URL of the previous page of results. If this field isn't present, you're at the start of the list."},"self":{"type":"string","format":"uri","description":"The URL of the current page of results."},"next":{"type":"string","format":"uri","description":"The URL of the next page of results. If this field isn't present, you're at the end of the list."},"count":{"type":"number","description":"The number of items in the entire list, i.e., across all pages."}}}}}}}}},{"responseCode":"400","schema":{"description":"","content":{"application/json":{"schema":{"type":"object","example":{"errors":[{"field":"field_name","message":"error message"}]},"refName":"ErrorResponse","modelName":"ErrorResponse","properties":{"errors":{"type":"array","items":{"type":"object","properties":{"message":{"type":"string","description":"An error message."},"field":{"description":"When applicable, this property value will be the field that generated the error.","nullable":true,"type":"string"},"help":{"type":"object","description":"When applicable, this property value will be helper text or a link to documentation to help you troubleshoot the error."}}}},"id":{"type":"string","description":"When applicable, this property value will be an error ID."}}}}},"refName":"#/components/responses/Stats400","modelName":"__components_responses_Stats400"}},{"responseCode":"404","schema":{"description":""}}]
```

Get Automation Stats by ID

```js
const client = require("@sendgrid/client");
client.setApiKey(process.env.SENDGRID_API_KEY);

const id = "id";
const queryParams = {
  aggregated_by: "total",
  end_date: "2021-12-31",
  start_date: "2021-01-01",
  timezone: "UTC",
};

const request = {
  url: `/v3/marketing/stats/automations/${id}`,
  method: "GET",
  qs: queryParams,
};

client
  .request(request)
  .then(([response, body]) => {
    console.log(response.statusCode);
    console.log(response.body);
  })
  .catch((error) => {
    console.error(error);
  });
```

```python
import os
from sendgrid import SendGridAPIClient


sg = SendGridAPIClient(os.environ.get("SENDGRID_API_KEY"))

id = "id"
params = {
    "aggregated_by": "total",
    "start_date": "2021-01-01",
    "end_date": "2021-12-31",
    "timezone": "UTC",
}

response = sg.client.marketing.stats.automations._(id).get(query_params=params)

print(response.status_code)
print(response.body)
print(response.headers)
```

```csharp
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using SendGrid;

public class Program {
    public static async Task Main() {
        string apiKey = Environment.GetEnvironmentVariable("SENDGRID_API_KEY");
        var client = new SendGridClient(apiKey);

        var id = "id";
        var queryParams =
            @"{'aggregated_by': 'total', 'start_date': '2021-01-01', 'end_date': '2021-12-31', 'timezone': 'UTC'}";

        var response = await client.RequestAsync(
            method: SendGridClient.Method.GET,
            urlPath: $"marketing/stats/automations/{id}",
            queryParams: queryParams);

        Console.WriteLine(response.StatusCode);
        Console.WriteLine(response.Body.ReadAsStringAsync().Result);
        Console.WriteLine(response.Headers.ToString());
    }
}
```

```java
import com.sendgrid.*;
import java.io.IOException;

public class Example {
    public static void main(String[] args) throws IOException {
        try {
            SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY"));
            Request request = new Request();
            request.setMethod(Method.GET);
            request.setEndpoint("/marketing/stats/automations/id");
            request.addQueryParam("aggregated_by", "total");
            request.addQueryParam("start_date", "2021-01-01");
            request.addQueryParam("end_date", "2021-12-31");
            request.addQueryParam("timezone", "UTC");
            Response response = sg.api(request);
            System.out.println(response.getStatusCode());
            System.out.println(response.getBody());
            System.out.println(response.getHeaders());
        } catch (IOException ex) {
            throw ex;
        }
    }
}
```

```go
package main

import (
	"fmt"
	"github.com/sendgrid/sendgrid-go"
	"os"
)

func main() {
	apiKey := os.Getenv("SENDGRID_API_KEY")
	host := "https://api.sendgrid.com"
	request := sendgrid.GetRequest(apiKey, "/v3/marketing/stats/automations/id", host)
	request.Method = "GET"
	queryParams := make(map[string]string)
	queryParams["aggregated_by"] = "total"
	queryParams["start_date"] = "2021-01-01"
	queryParams["end_date"] = "2021-12-31"
	queryParams["timezone"] = "UTC"
	request.QueryParams = queryParams
	response, err := sendgrid.API(request)
	if err != nil {
		fmt.Println(err.Error())
		os.Exit(1)
	} else {
		fmt.Println(response.StatusCode)
		fmt.Println(response.Body)
		fmt.Println(response.Headers)
	}
}
```

```php
<?php
// Uncomment the next line if you're using a dependency loader (such as Composer) (recommended)
// require 'vendor/autoload.php';

// Uncomment next line if you're not using a dependency loader (such as Composer)
// require_once '<PATH TO>/sendgrid-php.php';

$apiKey = getenv("SENDGRID_API_KEY");
$sg = new \SendGrid($apiKey);
$query_params = json_decode('{
    "aggregated_by": "total",
    "start_date": "2021-01-01",
    "end_date": "2021-12-31",
    "timezone": "UTC"
}');
$id = "id";

try {
    $response = $sg->client
        ->marketing()
        ->stats()
        ->automations()
        ->_($id)
        ->get(null, $query_params);
    print $response->statusCode() . "\n";
    print_r($response->headers());
    print $response->body() . "\n";
} catch (Exception $ex) {
    echo "Caught exception: " . $ex->getMessage();
}
```

```ruby
require 'sendgrid-ruby'
include SendGrid

sg = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY'])
id = "id"
params = JSON.parse('{
  "aggregated_by": "total",
  "start_date": "2021-01-01",
  "end_date": "2021-12-31",
  "timezone": "UTC"
}')

response = sg.client.marketing.stats.automations._(id).get(query_params: params)
puts response.status_code
puts response.headers
puts response.body
```

```bash
curl -G -X GET "https://api.sendgrid.com/v3/marketing/stats/automations/id?aggregated_by=total&start_date=2021-01-01&end_date=2021-12-31&timezone=UTC" \
--header "Authorization: Bearer $SENDGRID_API_KEY"
```
