---
title: Send custom events with our Event API
source: https://docs.newrelic.com/docs/data-apis/ingest-apis/event-api/introduction-event-api
---

The Event API lets you send custom [event data](https://docs.newrelic.com/docs/using-new-relic/data/understand-data/new-relic-data-types#event-data) to New Relic. These events can then be queried and charted.

Want to try out our Event API? [Create a New Relic account](https://newrelic.com/signup) for free! No credit card required.

Related content:

-   Learn about [all options for reporting custom events](https://docs.newrelic.com/docs/insights/insights-data-sources/custom-data/report-custom-event-data).
-   For how to add attributes to existing events, see [Add custom attributes](https://docs.newrelic.com/docs/agents/manage-apm-agents/agent-data/collect-custom-attributes).

## Why use the Event API? [#overview]

Our Event API is one option for reporting custom data. Another option is reporting custom attributes. For an overview of why you'd use the Event API versus other options, see [Custom events and attributes](https://docs.newrelic.com/docs/data-apis/custom-data/custom-events/report-custom-event-data#using-custom-events).

## Requirements [#requirements]

For Event API limits and restricted attributes, see [Limits](#limits).

Ensure outbound connectivity on TCP port 443 is allowed to the [CIDR range](https://docs.newrelic.com/docs/using-new-relic/cross-product-functions/install-configure/networks/#infrastructure) that matches your [region](https://docs.newrelic.com/docs/using-new-relic/welcome-new-relic/get-started/our-eu-us-region-data-centers). The preferred configuration method is to use the DNS name `insights-collector.newrelic.com` (US, default), `insights-collector.eu01.nr-data.net` (EU), or `insights-collector.jp.nr-data.net` (JP).

## Example of submitting and querying a custom event [#example-use-case]

Here's an example of the Event API in action:

**Calling the Event API from a Ruby app**

Custom events can be inserted through the [agent APIs](https://docs.newrelic.com/docs/data-apis/custom-data/custom-events/report-custom-event-data#ways) or directly via the Event API. The following example shows how to send a custom event type `CLIRun`, which tracks when a command line tool written in Ruby has its process exit due to an exception.

````ruby
# Hook into the runtime 'at_exit' event
at_exit do
  # Name the custom event
  payload = { 'eventType' => 'CLIRun' }

  # Check to see if the process is exiting due to an error
  if $!.nil? || $!.is_a?(SystemExit) && $!.success?
    payload[:status] = 0
  else
    # Gather any known errors
    errors = ""
    (Thread.current[:errors] ||= []).each do |err|
      errors += "#{err}\n"
    end
    payload[:errors] = errors
  end

  # Send the errors to New Relic as a custom event
  insights_url = URI.parse("https://insights-collector.newrelic.com/v1/accounts/YOUR_ACCOUNT_ID/events")
  headers = { "Api-Key" => "YOUR_LICENSE_KEY", "content-type" => "application/json" }

  http = Net::HTTP.new(insights_url.host, insights_url.port)
  http.use_ssl = true
  request = Net::HTTP::Post.new(insights_url.request_uri, headers)
  request.body = payload.to_json

  puts "Sending run summary to New Relic: #{payload.to_json}"
  begin
    response = http.request(request)
    puts "Response from New Relic: #{response.body}"
  rescue Exception => e
    puts "There was an error posting to New Relic. Error: #{e.inspect}"
  end
end
```

Then you could run a NRQL query to get more detail about that custom event, like:

```sql
SELECT count(*) FROM CLIRun FACET errors SINCE 1 week ago
```

````

## How to use the Event API [#workflow]

The Event API is an asynchronous endpoint. This allows you to send a very large volume of POSTS, reliably, with very low response latency.

> #### 💡 TIP
>
> If your organization hosts data in the EU or JP data center, ensure you're using the proper regional endpoints. See [EU region endpoints](https://docs.newrelic.com/docs/accounts/accounts-billing/account-setup/choose-your-data-center/#eu-endpoints) or [JP region endpoints](https://docs.newrelic.com/docs/accounts/accounts-billing/account-setup/choose-your-data-center/#jp-endpoints).

To send a custom event to a New Relic account:

1.  Get a license key for the account you want to report data to.
2.  Before creating custom events or attributes, review our list of [reserved terms used by NRQL](https://docs.newrelic.com/docs/data-apis/custom-data/custom-events/data-requirements-limits-custom-event-data/#reserved-words).
3.  [Generate JSON](#instrument) for the event by instrumenting your application, querying an API, or some other method.
4.  [Submit a compressed JSON payload](#submit-event) (for example, `gzip` or `deflate`) to the HTTPS endpoint using curl in a **POST** request.
5.  Recommendation: Set up [NRQL alert conditions](https://docs.newrelic.com/docs/alerts/new-relic-alerts/defining-conditions/create-alert-conditions-nrql-queries) to notify you when [parsing errors](#errors-parsing) occur.

The Event API [limits the size, rate, and characters](#limits) allowed in custom events. Also, like other data available in NRQL, custom events cannot be updated or deleted after they're created. If you have problems with your custom event, follow the [troubleshooting procedures](#verify) or create a new custom event.

## Format the JSON [#instrument]

The Event API accepts specific formats for attributes included in the payload. Only float or string values are allowed.

**JSON format guidelines**

When defining attributes for your custom events, follow these JSON format guidelines.

| Attributes              | JSON format guidelines                                                                                                                                                                                                                                                                                                                                         |
| ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `eventType`             | **Required:** The event's name.                                                                                                                                                                                                                                                                                                                                |
| Float and string values | Float value format: `"label":value` String value format: `"label":"value"`                                                                                                                                                                                                                                                                                     |
| Data types              | The API only accepts key-value pairs, not map/object or array values. Supported data types for this API are strings and numbers (integers or floats). For more information, see [Data requirements](https://docs.newrelic.com/docs/insights/insights-data-sources/custom-data/insights-custom-data-requirements-limits).                                       |
| Digits in strings       | For performance-related reasons, we do not cast values submitted to the API. For example, we treat `123` as a number and `"123"` as a string. The database will only store up to 64 bit numbers. Any numbers larger than 64 bits will be truncated.                                                                                                            |
| Dates                   | For attributes that contain date information, use an unformatted Unix timestamp in the [data formatter](https://docs.newrelic.com/docs/insights/use-insights-ui/manage-account-data/data-formatter-set-default-formats-numeric-values). You can [define the date attribute](#timestamp) either in seconds or in milliseconds, both relative to the Unix epoch. |
| Time                    | Unless otherwise specified, the timestamp for a submitted event is the time it was submitted to New Relic. To specify a different time for the event, use the [`timestamp` attribute](#timestamp).                                                                                                                                                             |

**JSON example**

Here is an example of a typical JSON data set for sending with the API. This call sends two **Purchase** type events as a JSON array. You can add multiple events in a single HTTP call using a JSON array.

````json
[
    {
        "eventType": "Purchase",
        "account": 3,
        "amount": 259.54
    },
    {
        "eventType": "Purchase",
        "account": 5,
        "amount": 12309,
        "product": "Item"
    }
]
```

When generating the JSON, make sure your attributes are [properly formatted](/docs/insights/new-relic-insights/decorating-events/insights-custom-attributes).

````

**Limits and restricted characters**

The following size and rate limits apply to events sent via the Event API:

-   Payload total size: **1MB(10^6 bytes) maximum per POST**. We highly recommend using compression.

-   The payload must be encoded as **UTF-8**.

-   Maximum number of attributes per event: 255

-   Maximum length of attribute name: 255 characters

-   Maximum length of attribute value: 4096 characters

-   There are [rate limits on the number of HTTP requests per minute](#post-limit) sent to the Event API.

    Some attributes have additional restrictions:

-   `accountId`: This is a reserved attribute name. If it is included, it will be dropped during ingest.

-   `entity.guid`, `entity.name`, and `entity.type`: These attributes are used internally to identify entities. Any values submitted with these keys in the attributes section of a metric data point may cause undefined behavior such as missing entities in the UI or telemetry not associating with the expected entities. For more information please refer to [Entity synthesis](https://docs.newrelic.com/docs/new-relic-one/use-new-relic-one/core-concepts/what-entity-new-relic/#entity-synthesis).

-   [`appId`](https://docs.newrelic.com/docs/apis/rest-api-v2/requirements/find-product-id#apm): Value must be an integer. If it is not an integer, the attribute name and value will be dropped during ingest.

-   `eventType`: This attribute can be a combination of alphanumeric characters, `_` underscores, and `:` colons.

-   `timestamp`: This attribute must be a Unix epoch timestamp, defined in either seconds or milliseconds.

## Submit the custom event [#submit-event]

Data submitted to the Event API uses a compressed JSON format in a simple HTTPS POST request. This example uses `gzip`, but you can also use `deflate`.

**Linux/bash example**

````bash
gzip -c example_events.json | curl -X POST -H "Content-Type: application/json" \
-H "Api-Key: YOUR_LICENSE_KEY" -H "Content-Encoding: gzip" \
https://insights-collector.newrelic.com/v1/accounts/YOUR_ACCOUNT_ID/events --data-binary @-
```

````

**Windows/PowerShell example**

````powershell
$accountId = "YOUR_ACCOUNT_ID"
$insertkey = "YOUR_LICENSE_KEY"
# Replace with your custom event for the body
$body = '[{"eventType": "powershell", "account": 4, "amount": 123, "fileLocation": "c:\\temp2", "zipped": "true" }]'

$headers = @{}
$headers.Add("Api-Key", "$insertkey")
$headers.Add("Content-Encoding", "gzip")


$encoding = [System.Text.Encoding]::UTF8
$enc_data = $encoding.GetBytes($body)

$output = [System.IO.MemoryStream]::new()
$gzipStream = New-Object System.IO.Compression.GzipStream $output, ([IO.Compression.CompressionMode]::Compress)

$gzipStream.Write($enc_data, 0, $enc_data.Length)
$gzipStream.Close()
$gzipBody = $output.ToArray()

Invoke-WebRequest -Headers $headers -Method Post -Body $gzipBody  "https://insights-collector.newrelic.com/v1/accounts/$accountId/events"
```

````

> #### ⚠️ IMPORTANT
>
> Always use compression with every payload. This allows you to send more data, and it saves resources during parsing.

Before generating your HTTP request, make sure it is [properly formatted](https://docs.newrelic.com/docs/insights/new-relic-insights/decorating-events/insights-custom-attributes), including:

-   The `Api-Key` contains the correct license key.
-   The `Content-Type` is `application/json`.
-   The request uses POST only. The API does not accept PUT and GET requests.

The API supports [HTTP/1.1 persistent connections](https://www.w3.org/Protocols/rfc2616/rfc2616-sec8.html). This is helpful to manage client-side performance under heavy event loads.

## Verify or troubleshoot request response [#verify]

The Event API follows a two-step process to process requests:

1.  The Event API synchronously acknowledges or rejects the request based on validation of the headers and payload size.
2.  The Event API asynchronously parses the payload after a successful HTTP response is provided to the client. This may generate an error due to missing or malformed data. These are classified as submission errors or parsing errors.

All successful submissions receive a `200` response, regardless of any data errors that may exist within the payload. The response includes a `uuid`, which is a unique ID created for each request. The `uuid` also appears in any error events created for the request.

Other potential issues:

-   10-second timeout: API calls exceeding 10 seconds will time out.
-   Large payloads: Payloads exceeding 100 KB may see increased response times.

Recommendation:In addition to checking for a success message, create a NRQL query of your data to verify it's available.

**Success response code**

| Success message | Comments                                                                          |
| --------------- | --------------------------------------------------------------------------------- |
| 200             | ````json {"success":true,"uuid":"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"} ```  ```` |

**Submission errors**

Payloads with submission errors are handled and returned to the sender through an HTTP response code.

To troubleshoot payload submission errors, refer to these HTTP response codes.

| Submission errors | Troubleshooting                                                                                                                                                         |
| ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 400               | Missing or invalid content length: Unable to process empty request.                                                                                                     |
| 403               | Missing or invalid key: Invalid license key. Register a valid license key. You must use a key of the `License` type. `Browser`, `Mobile`, or `User` keys will not work. |
| 408               | Request timed out: Request took too long to process.                                                                                                                    |
| 413               | Content too large: Request is too large to process. Refer to the limits and restricted characters to troubleshoot.                                                      |
| 415               | Invalid content type: Must be application/JSON. The Event API accepts any content type except multi-part/related and assumes it can be parsed to JSON.                  |
| 429               | Too many requests due to rate limiting.                                                                                                                                 |
| 503               | Service temporarily unavailable: Retry request                                                                                                                          |

**Parsing errors**

Parsing errors occur if:

-   An event is sent within a payload, but it is either missing data or is exceeding maximum limits. New Relic will drop the individual event from the payload, generate an [`NrIntegrationError` event](https://docs.newrelic.com/docs/telemetry-data-platform/manage-data/nrintegrationerror), and process the rest.
-   The JSON payload includes malformed JSON or missing required data.

    Payloads with parsing errors receive a `200` response to indicate a successful submission. To help resolve parsing errors, a new `NrIntegrationError` event type is created. All parsing errors are due to NRQL queries. For error messages related to dropped events, New Relic will include the number of events that were dropped as part of the message.

    To troubleshoot requests with parsing errors, refer to these error messages.

    | Parsing errors                                                                            | Troubleshooting                                                                               |
    | ----------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- |
    | X event(s) rejected because attribute `appId` was not an integer                          | An `appId` attribute has a non-integer value, such as a decimal value or string.              |
    | X event(s) rejected because `eventType` cannot contain the following characters: `[., \]` | An `eventType` attributed included an invalid character, such as a period or backslash.       |
    | X event(s) rejected because attribute is missing attribute name                           | An attribute name was set to null or an empty string.                                         |
    | X event(s) rejected because attribute name exceeded maximum length                        | An attribute name has more than 255 characters.                                               |
    | X event(s) rejected because attribute value exceeded maximum length                       | An attribute value was longer than 4096 characters.                                           |
    | X event(s) rejected because event exceeded maximum number of attributes                   | An event has more than 255 attributes.                                                        |
    | X event(s) rejected because missing required attributes `eventType`                       | The `eventType` attribute is required for the custom event.                                   |
    | Error parsing JSON payload                                                                | There was an error parsing the request JSON because of formatting problems or corrupted data. |

## Query and alert with NrIntegrationError [#nrIntegration]

The [`NrIntegrationError` event](https://docs.newrelic.com/docs/telemetry-data-platform/manage-data/nrintegrationerror) allows you to query and set alerts on custom data being sent to your New Relic account. Recommendation: To get alerts for parsing errors, [create a NRQL alert condition](https://docs.newrelic.com/docs/alerts/new-relic-alerts/defining-conditions/create-alert-conditions-nrql-queries) for `NrIntegrationError`. Use this example NRQL query:

```sql
SELECT message FROM NrIntegrationError WHERE newRelicFeature = 'Event API' AND category = 'EventApiException'
```

| NrIntegrationError attributes | Troubleshooting                                                                                                                                                                                                                                                                                                                                                                      |
| ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `timestamp`                   | The timestamp when the request was received. The `timestamp` attribute takes a 64-bit integer Unix timestamp within the last 24 hours. You can define timestamps either in seconds or in milliseconds, both relative to the Unix epoch. Do not use a decimal for the timestamp. If a decimal is used, the attribute will default to the timestamp when the custom event was created. |
| `newRelicFeature`             | The name of the feature experiencing errors. For all custom event parsing errors, this will be `Event API`.                                                                                                                                                                                                                                                                          |
| `apiKeyPrefix`                | The first six characters of the license key used for the request that generated an error.                                                                                                                                                                                                                                                                                            |
| `requestId`                   | The `uuid` returned by the the API for the request that generated an error.                                                                                                                                                                                                                                                                                                          |
| `category`                    | The category of the error. For custom events, this is `EventApiException`.                                                                                                                                                                                                                                                                                                           |
| `message`                     | Contents of the error message.                                                                                                                                                                                                                                                                                                                                                       |
| `name`                        | The error's name. For custom events, this is always `EventValidationException`.                                                                                                                                                                                                                                                                                                      |
| `eventTypeSample`             | One of the event types that generated the error, when available.                                                                                                                                                                                                                                                                                                                     |

## Find your data [#find-data]

To find data sent via the Event API (and from integrations that use this API), you can query it. For example, to query a custom event using [NRQL](https://docs.newrelic.com/docs/query-data/nrql-new-relic-query-language/getting-started/introduction-nrql), you would run:

```sql
SELECT * FROM YOUR_CUSTOM_EVENT
```

For more on how to query, see [Query data](https://docs.newrelic.com/docs/using-new-relic/data/understand-data/query-new-relic-data).

## Limit on HTTP requests [#post-limit]

The Event API has a rate limit of 100,000 HTTP requests (POSTs) per minute, per account. (Note that this is **not** a limit on the number of events per minute; only on the number of POSTs per minute.)

This limit helps ensure that large traffic spikes in accounts across our multi-tenant platform do not negatively affect how the service performs for you.

If your API usage exceeds 100k POSTs in a 1-minute window, we will reject subsequent API requests with a 429 response code for the remainder of the 1-minute window. At the end of the 1-minute window, the counter will be reset and allow traffic to resume.

This limit is intended to be an upper threshold that you shouldn't hit under normal scenarios. If you have a high number of 429 responses, consider using the API less. If you are expecting a higher-than-normal activity level in the near future and want to prepare for that, [contact technical support](https://support.newrelic.com/).
