The [Reports service](https://developers.google.com/doubleclick-advertisers/current/reports) for the Campaign Manager 360 API allows you to create and update Report Builder reports using report resource objects. A report resource outlines basic information about a report to be run, as well as the structure of the report output.

This guide details how to programmatically create and update Report Builder reports via the Reports service.

> [!NOTE]
> **Note:** Building a valid report is not a trivial task. Some subsets of dimensions and metrics are valid only in specific combinations. We therefore recommend that you initially build reports with [Report Builder](https://www.google.com/analytics/dfa/) and then clone and modify these reports through the API.

## Configure a report resource

The first step in creating or updating a Report Builder report is to configure a report resource object. If you're creating a new report, you'll start with an empty resource and set the necessary fields. If you're updating an existing report, you have a choice of:

1. **Preferred** : Performing a [partial update](https://developers.google.com/doubleclick-advertisers/performance#patch). Using this approach, you'll start with an empty resource and set the fields you'd like to change. A partial update only saves changes to fields you specify.
2. Performing a full update. Using this approach, you'll load an existing report resource and directly modify its fields. A full update always saves all of the report's fields.

The exact contents of a report resource vary depending on the [type of report](https://support.google.com/dcm/answer/2823873) you're configuring. Even so, there are a few fields that are common to all report types:

| Field | Description |
|---|---|
| **Required fields** ||
| name | The name of the report. |
| type | The type of the report. |
| **Optional fields** ||
| delivery | The report's email delivery settings. |
| fileName | The filename used when generating report files for this report. |
| format | The output format of the report, either CSV or Excel. |
| schedule | A schedule used to run your report on a recurring basis. |

These common fields make up the skeleton of your report. The example below illustrates the creation of a new standard report resource:

### C#

    Report report = new Report();

    // Set the required fields "name" and "type".
    report.Name = "Example standard report";
    report.Type = "STANDARD";

    // Set optional fields.
    report.FileName = "example_report";
    report.Format = "CSV";

### Java

    Report report = new Report();

    // Set the required fields "name" and "type".
    report.setName("Example standard report");
    report.setType("STANDARD");

    // Set optional fields
    report.setFileName("example_report");
    report.setFormat("CSV");

### PHP

    $report = new Google_Service_Dfareporting_Report();

    // Set the required fields "name" and "type".
    $report->setName('Example standard report');
    $report->setType('STANDARD');

    // Set optional fields.
    $report->setFileName('example_report');
    $report->setFormat('CSV');

### Python

    report = {
        # Set the required fields "name" and "type".
        'name': 'Example Standard Report',
        'type': 'STANDARD',
        # Set optional fields.
        'fileName': 'example_report',
        'format': 'CSV'
    }

### Ruby

    report = DfareportingUtils::API_NAMESPACE::Report.new(
      # Set the required fields "name" and "type".
      name: 'Example Standard Report',
      type: 'STANDARD',
      # Set optional fields.
      file_name: 'example_report',
      format: 'CSV'
    )

## Define the report criteria

Once you've chosen a report type and configured common fields, the next step is to define the report criteria. The report criteria are used to limit the scope of your report, ensuring only relevant information is returned. It also defines the structure of the report output.

The criteria used depends on the type of report. The relationship between report type and criteria is explained in the following table:

| Report type | Criteria field |
|---|---|
| [STANDARD](https://support.google.com/dcm/answer/2823849) | [criteria](https://developers.google.com/doubleclick-advertisers/current/reports#Report.FIELDS.criteria) |
| [REACH](https://support.google.com/dcm/answer/2823516) | [reachCriteria](https://developers.google.com/doubleclick-advertisers/current/reports#Report.FIELDS.reach_criteria) |
| [PATH_TO_CONVERSION](https://support.google.com/dcm/answer/2823644) | [pathToConversionCriteria](https://developers.google.com/doubleclick-advertisers/current/reports#Report.FIELDS.path_to_conversion_criteria) |
| [FLOODLIGHT](https://support.google.com/dcm/answer/2823790) | [floodlightCriteria](https://developers.google.com/doubleclick-advertisers/current/reports#Report.FIELDS.floodlight_criteria) |
| [CROSS_DIMENSION_REACH](https://support.google.com/dcm/answer/2823849) | [crossDimensionReachCriteria](https://developers.google.com/doubleclick-advertisers/current/reports#Report.FIELDS.cross_media_reach_criteria) |

While each of these type-specific criteria expose a slightly different set of fields, there is a set of common criteria fields that are generally useful for controlling report output:

| Field | Description |
|---|---|
| dateRange | The dates for which this report should be run. Can be used to specify either a custom start and end date or a [relative date range](https://developers.google.com/doubleclick-advertisers/current/File#DateRange.FIELDS.relative_date_range). > [!NOTE] > **Note:** When running reports via the API, relative date ranges like `YESTERDAY` are resolved in the America/Los Angeles time zone. This may cause unexpected results for users in different time zones. |
| dimensionFilters | A list of filters that restrict the results returned. See the [query filter values](https://developers.google.com/doubleclick-advertisers/guides/create_reports#filter_values) section for more information on configuring filters. |
| dimensions | A list of Campaign Manager 360 elements to include in the report output. |
| metricNames | Standard units of measure to include in the report output. |

See the section on [determining field compatibility](https://developers.google.com/doubleclick-advertisers/guides/create_reports#field_compatibility) for more information on choosing dimensions, metrics, and filters for your report. Additional type-specific criteria fields are explained in the [reference documentation](https://developers.google.com/doubleclick-advertisers/current/reports) and the [help center](https://support.google.com/dcm/answer/2823873).

The example below adds a basic criteria to our standard report resource:

### C#

    // Define a date range to report on. This example uses explicit start and
    // end dates to mimic the "LAST_30_DAYS" relative date range.
    DateRange dateRange = new DateRange();
    dateRange.EndDate = DateTime.Now.ToString("yyyy-MM-dd");
    dateRange.StartDate = DateTime.Now.AddDays(-30).ToString("yyyy-MM-dd");

    // Create a report criteria.
    SortedDimension dimension = new SortedDimension();
    dimension.Name = "advertiser";

    Report.CriteriaData criteria = new Report.CriteriaData();
    criteria.DateRange = dateRange;
    criteria.Dimensions = new List<SortedDimension>() { dimension };
    criteria.MetricNames = new List<string>() {
      "clicks",
      "impressions"
    };

    // Add the criteria to the report resource.
    report.Criteria = criteria;

### Java

    // Define a date range to report on. This example uses explicit start and end dates to mimic
    // the "LAST_MONTH" relative date range.
    DateRange dateRange = new DateRange();
    dateRange.setEndDate(new DateTime(true, System.currentTimeMillis(), null));

    Calendar lastMonth = Calendar.getInstance();
    lastMonth.add(Calendar.MONTH, -1);
    dateRange.setStartDate(new DateTime(true, lastMonth.getTimeInMillis(), null));

    // Create a report criteria.
    Report.Criteria criteria = new Report.Criteria();
    criteria.setDateRange(dateRange);
    criteria.setDimensions(Lists.newArrayList(new SortedDimension().setName("advertiser")));
    criteria.setMetricNames(Lists.newArrayList("clicks", "impressions"));

    // Add the criteria to the report resource.
    report.setCriteria(criteria);

### PHP

    // Define a date range to report on. This example uses explicit start and
    // end dates to mimic the "LAST_30_DAYS" relative date range.
    $dateRange = new Google_Service_Dfareporting_DateRange();
    $dateRange->setStartDate(
        date('Y-m-d', mktime(0, 0, 0, date('m'), date('d') - 30, date('Y')))
    );
    $dateRange->setEndDate(date('Y-m-d'));

    // Create a report criteria.
    $dimension = new Google_Service_Dfareporting_SortedDimension();
    $dimension->setName('advertiser');

    $criteria = new Google_Service_Dfareporting_ReportCriteria();
    $criteria->setDateRange($dateRange);
    $criteria->setDimensions([$dimension]);
    $criteria->setMetricNames(['clicks', 'impressions']);

    // Add the criteria to the report resource.
    $report->setCriteria($criteria);

### Python

    # Define a date range to report on. This example uses explicit start and end
    # dates to mimic the "LAST_30_DAYS" relative date range.
    end_date = datetime.date.today()
    start_date = end_date - datetime.timedelta(days=30)

    # Create a report criteria.
    criteria = {
        'dateRange': {
            'startDate': start_date.strftime('%Y-%m-%d'),
            'endDate': end_date.strftime('%Y-%m-%d')
        },
        'dimensions': [{
            'name': 'advertiser'
        }],
        'metricNames': ['clicks', 'impressions']
    }

    # Add the criteria to the report resource.
    report['criteria'] = criteria

### Ruby

    # Define a date range to report on. This example uses explicit start and end
    # dates to mimic the "LAST_30_DAYS" relative date range.
    start_date = DateTime.now.prev_day(30).strftime('%Y-%m-%d')
    end_date = DateTime.now.strftime('%Y-%m-%d')

    # Create a report criteria
    criteria = DfareportingUtils::API_NAMESPACE::Report::Criteria.new(
      date_range: DfareportingUtils::API_NAMESPACE::DateRange.new(
        start_date: start_date,
        end_date: end_date
      ),
      dimensions: [
        DfareportingUtils::API_NAMESPACE::SortedDimension.new(
          name: 'advertiser'
        )
      ],
      metric_names: ['clicks', 'impressions']
    )

    # Add the criteria to the report resource.
    report.criteria = criteria

### Query filter values

When configuring filters for a report, you need to specify the exact values that the filters will use to restrict the report output. If you aren't sure what the possible values for a particular filter are, look them up using the [DimensionValues](https://developers.google.com/doubleclick-advertisers/current/DimensionValue) service.

A basic dimension values query contains a [dimension name](https://developers.google.com/doubleclick-advertisers/current/dimensionValues/query#DimensionValueRequest.FIELDS.dimension_name), as well as a [start date](https://developers.google.com/doubleclick-advertisers/current/dimensionValues/query#DimensionValueRequest.FIELDS.start_date) and [end date](https://developers.google.com/doubleclick-advertisers/current/dimensionValues/query#DimensionValueRequest.FIELDS.end_date). The start and end dates limit the response to values valid within that time period. [Additional filters](https://developers.google.com/doubleclick-advertisers/current/dimensionValues/query#DimensionValueRequest.FIELDS.filters) can be specified if you need to limit the query results further.

The below example looks up valid advertiser filter values during the dates that our report will run and adds them to the report criteria:

### C#

    // Query advertiser dimension values for report run dates.
    DimensionValueRequest request = new DimensionValueRequest();
    request.StartDate = report.Criteria.DateRange.StartDate;
    request.EndDate = report.Criteria.DateRange.EndDate;
    request.DimensionName = "advertiser";

    DimensionValueList values =
        service.DimensionValues.Query(request, profileId).Execute();

    if (values.Items.Any()) {
      // Add a value as a filter to the report criteria.
      report.Criteria.DimensionFilters = new List<DimensionValue>() {
        values.Items[0]
      };
    }

### Java

    // Query advertiser dimension values for report run dates.
    DimensionValueRequest request = new DimensionValueRequest();
    request.setStartDate(report.getCriteria().getDateRange().getStartDate());
    request.setEndDate(report.getCriteria().getDateRange().getEndDate());
    request.setDimensionName("advertiser");

    DimensionValueList values = reporting.dimensionValues().query(profileId, request).execute();

    if (!values.getItems().isEmpty()) {
      // Add a value as a filter to the report criteria.
      List<DimensionValue> filters = Lists.newArrayList(values.getItems().get(0));
      report.getCriteria().setDimensionFilters(filters);
    }

### PHP

    // Query advertiser dimension values for report run dates.
    $request = new Google_Service_Dfareporting_DimensionValueRequest();
    $request->setStartDate(
        $report->getCriteria()->getDateRange()->getStartDate()
    );
    $request->setEndDate(
        $report->getCriteria()->getDateRange()->getEndDate()
    );
    $request->setDimensionName('advertiser');

    $values =
        $this->service->dimensionValues->query($userProfileId, $request);

    if (!empty($values->getItems())) {
        // Add a value as a filter to the report criteria.
        $report->getCriteria()->setDimensionFilters([$values->getItems()[0]]);
    }

### Python

    # Query advertiser dimension values for report run dates.
    request = {
        'dimensionName': 'advertiser',
        'endDate': report['criteria']['dateRange']['endDate'],
        'startDate': report['criteria']['dateRange']['startDate']
    }

    values = service.dimensionValues().query(
        profileId=profile_id, body=request).execute()

    if values['items']:
      # Add a value as a filter to the report criteria.
      report['criteria']['dimensionFilters'] = [values['items'][0]]

### Ruby

    # Query advertiser dimension values for report run dates.
    dimension = DfareportingUtils::API_NAMESPACE::DimensionValueRequest.new(
      dimension_name: 'advertiser',
      start_date: report.criteria.date_range.start_date,
      end_date: report.criteria.date_range.end_date
    )

    values = service.query_dimension_value(profile_id, dimension)

    unless values.items.empty?
      # Add a value as a filter to the report criteria.
      report.criteria.dimension_filters = [values.items.first]
    end

### Determine field compatibility

When configuring your report criteria, it's important to remember that not all combinations of metrics, dimensions, and filters are valid. You won't be allowed to save a report that contains an invalid combination, so it's important to ensure the fields you plan to use are compatible with one another.

As you build your report resource, you can pass it into the [Reports.compatibleFields](https://developers.google.com/doubleclick-advertisers/current#Reports.compatibleFields) service to see which fields are valid given the ones you've already selected. The configuration of the report will be analyzed, and a response containing the compatible dimensions, metrics, and filters will be returned. Since the fields in this response are not all guaranteed to be compatible with one another, you may need to make multiple requests to ensure all the fields you choose will work together.

The example below illustrates how to make a sample compatible fields request, using our report resource as input:

### C#

    CompatibleFields fields =
        service.Reports.CompatibleFields.Query(report, profileId).Execute();

    ReportCompatibleFields reportFields = fields.ReportCompatibleFields;

    if(reportFields.Dimensions.Any()) {
      // Add a compatible dimension to the report.
      Dimension dimension = reportFields.Dimensions[0];
      SortedDimension sortedDimension = new SortedDimension();
      sortedDimension.Name = dimension.Name;
      report.Criteria.Dimensions.Add(sortedDimension);
    } else if (reportFields.Metrics.Any()) {
      // Add a compatible metric to the report.
      Metric metric = reportFields.Metrics[0];
      report.Criteria.MetricNames.Add(metric.Name);
    }

### Java

    CompatibleFields fields = reporting.reports().compatibleFields()
        .query(profileId, report).execute();

    ReportCompatibleFields reportFields = fields.getReportCompatibleFields();

    if (!reportFields.getDimensions().isEmpty()) {
      // Add a compatible dimension to the report.
      Dimension dimension = reportFields.getDimensions().get(0);
      SortedDimension sortedDimension = new SortedDimension().setName(dimension.getName());
      report.getCriteria().getDimensions().add(sortedDimension);
    } else if (!reportFields.getMetrics().isEmpty()) {
      // Add a compatible metric to the report.
      Metric metric = reportFields.getMetrics().get(0);
      report.getCriteria().getMetricNames().add(metric.getName());
    }

### PHP

    $fields = $this->service->reports_compatibleFields->query(
        $userProfileId,
        $report
    );

    $reportFields = $fields->getReportCompatibleFields();

    if (!empty($reportFields->getDimensions())) {
        // Add a compatible dimension to the report.
        $dimension = $reportFields->getDimensions()[0];
        $sortedDimension = new Google_Service_Dfareporting_SortedDimension();
        $sortedDimension->setName($dimension->getName());
        $report->getCriteria()->setDimensions(
            array_merge(
                $report->getCriteria()->getDimensions(),
                [$sortedDimension]
            )
        );
    } elseif (!empty($reportFields->getMetrics())) {
        // Add a compatible metric to the report.
        $metric = $reportFields->getMetrics()[0];
        $report->getCriteria()->setMetricNames(
            array_merge(
                $report->getCriteria()->getMetricNames(),
                [$metric->getName()]
            )
        );
    }

### Python

    fields = service.reports().compatibleFields().query(
        profileId=profile_id, body=report).execute()

    report_fields = fields['reportCompatibleFields']

    if report_fields['dimensions']:
      # Add a compatible dimension to the report.
      report['criteria']['dimensions'].append({
          'name': report_fields['dimensions'][0]['name']
      })
    elif report_fields['metrics']:
      # Add a compatible metric to the report.
      report['criteria']['metricNames'].append(
          report_fields['metrics'][0]['name'])

### Ruby

    fields = service.query_report_compatible_field(profile_id, report)

    report_fields = fields.report_compatible_fields

    if report_fields.dimensions.any?
      # Add a compatible dimension to the report.
      report.criteria.dimensions <<
        DfareportingUtils::API_NAMESPACE::SortedDimension.new(
          name: report_fields.dimensions.first.name
        )
    elsif report_fields.metrics.any?
      # Add a compatible metric to the report.
      report.criteria.metric_names << report_fields.metrics.first.name
    end

## Save the report

The final step in this process is to save your report resource. If you're creating a new report, you can insert it with a call to [Reports.insert](https://developers.google.com/doubleclick-advertisers/current/reports/insert):

### C#

    Report insertedReport =
        service.Reports.Insert(report, profileId).Execute();

### Java

    Report insertedReport = reporting.reports().insert(profileId, report).execute();

### PHP

    $insertedReport =
        $this->service->reports->insert($userProfileId, $report);

### Python

    inserted_report = (
        service.reports().insert(profileId=str(profile_id), body=report).execute()
    )

### Ruby

    report = service.insert_report(profile_id, report)

You can save your changes by calling [Reports.update](https://developers.google.com/doubleclick-advertisers/current/reports/update):

### C#

    // Update an existing report.
    Report updatedReport =
        service.Reports.Update(report, profileId, report.Id).Execute();

### Java

    // Update an existing report.
    Report updatedReport = reporting.reports().update(profileId, report.getId(), report).execute();

### PHP

    # Update an existing report.
    $updatedReport =
        $this->service->reports->update($userProfileId, $report->getId(), $report)

### Python

    # Update an existing report.
    updated_report = service.reports().update(
        profileId=profile_id, reportId=report['id'], body=report).execute();

### Ruby

    # Update an existing report.
    updated_report = service.update_report(profile_id, report.id, report);

After a successful save request, a copy of the report resource will be returned in the response body. This resource will have a few new fields filled out, the most important of which is the [id field](https://developers.google.com/doubleclick-advertisers/current/reports#Report.FIELDS.id). This id is what you will use to refer to this report throughout the [rest of your workflow](https://developers.google.com/doubleclick-advertisers/guides/run_reports).