# Search recipients

## API Overview

> \[!WARNING]
>
> This covers the obsolete Legacy Marketing Campaigns API.

> \[!NOTE]
>
> For the most up-to-date information on the Contacts API, please visit the [new Marketing Campaigns Contacts API](/docs/sendgrid/api-reference/contacts).

The Contacts Recipients API allows you to manage your recipients. You can add, retrieve, update, and delete recipients, as well as get a count of all recipients and all billable recipients.

## Operation overview

```json
{"path":"https://api.sendgrid.com/v3/contactdb/recipients/search","method":"post","servers":[{"url":"https://api.sendgrid.com","description":"The Twilio SendGrid v3 API"}]}
```

Search using segment conditions without actually creating a segment.
Body contains a JSON object with `conditions`, a list of conditions as described below, and an optional `list_id`, which is a valid list ID for a list to limit the search on.

Valid operators for create and update depend on the type of the field for which you are searching.

* Dates:
  * `"eq"`, `"ne"`, `"lt"` (before), `"gt"` (after)
    * You may use MM/DD/YYYY for day granularity or an epoch for second granularity.
  * `"empty"`, `"not_empty"`
  * `"is within"`
    * You may use an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date format or the # of days.
* Text: `"contains"`, `"eq"` (is - matches the full field), `"ne"` (is not - matches any field where the entire field is not the condition value), `"empty"`, `"not_empty"`
* Numbers: `"eq"`, `"lt"`, `"gt"`, `"empty"`, `"not_empty"`
* Email Clicks and Opens: `"eq"` (opened), `"ne"` (not opened)

Field values must all be a string.

Search conditions using `"eq"` or `"ne"` for email clicks and opens should provide a "field" of either `clicks.campaign_identifier` or `opens.campaign_identifier`.

The condition value should be a string containing the id of a completed campaign.

Search conditions list may contain multiple conditions, joined by an `"and"` or `"or"` in the `"and_or"` field.

The first condition in the conditions list must have an empty `"and_or"`, and subsequent conditions must all specify an `"and_or"`.

## Operation details

### Authentication

API Key

### Headers

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

### Request body

```json
{"schema":{"type":"object","required":["list_id","conditions"],"example":{"list_id":-27497588,"conditions":[{"and_or":"","field":"birthday","value":"01/12/1985","operator":"eq"},{"and_or":"","field":"birthday","value":"01/12/1985","operator":"eq"},{"and_or":"","field":"birthday","value":"01/12/1985","operator":"eq"},{"and_or":"","field":"birthday","value":"01/12/1985","operator":"eq"}]},"properties":{"list_id":{"type":"integer","format":"int32"},"conditions":{"type":"array","description":"The conditions by which this segment should be created.","items":{"title":"ContactDB: Segments: Conditions","type":"object","required":["field","value","operator"],"refName":"ContactdbSegmentsConditions","modelName":"ContactdbSegmentsConditions","properties":{"field":{"type":"string"},"value":{"type":"string"},"operator":{"type":"string","enum":["eq","ne","lt","gt","contains"],"refName":"Operator","modelName":"Operator"},"and_or":{"type":"string","enum":["and","or",""],"refName":"AndOr","modelName":"AndOr"}}}}}},"encodingType":"application/json"}
```

### Responses

```json
[{"responseCode":"200","schema":{"description":"","content":{"application/json":{"schema":{"type":"object","properties":{"recipients":{"type":"array","items":{"type":"object","properties":{"created_at":{"type":"integer"},"email":{"type":"string"},"id":{"type":"string"},"last_emailed":{"type":"integer"},"last_clicked":{"type":"integer"},"last_opened":{"type":"integer"},"custom_fields":{"type":"array","items":{"type":"object","properties":{"id":{"type":"integer"},"name":{"type":"string"},"value":{"anyOf":[{"type":"integer"},{"type":"string"}]},"type":{"type":"string"}}}},"updated_at":{"type":"integer"},"first_name":{"type":"string"}}}},"recipient_count":{"type":"integer"}}},"examples":{"response":{"value":{"recipients":[{"created_at":-27901208,"email":"ut magna quis ipsum","id":"fugiat ad adipisicing ullamco","last_emailed":21626657},{"created_at":17466400,"email":"sunt irure","id":"et","last_clicked":-23135244,"last_opened":-44593357,"first_name":"est"},{"created_at":-34495329,"email":"reprehenderit incididunt velit Lorem esse","id":"esse Ut ad dolore","last_clicked":10164083,"last_opened":34443062},{"created_at":-37030673,"email":"amet deserunt fugiat voluptate","id":"et exercitation commodo id laborum","last_clicked":-10497425},{"created_at":3658435,"email":"labore veniam","id":"ad pariatur esse","last_opened":-84227501,"custom_fields":[{"id":-5765608,"name":"proident pariatur","value":"do in magna mollit","type":"dolore ut"},{"id":-31131201,"name":"laborum mollit","value":84434696,"type":"veniam"}],"updated_at":-56455352,"first_name":"Ut cupidatat nulla deserunt adipisicing","last_clicked":-52862671}],"recipient_count":65190677}}}}}}},{"responseCode":"400","schema":{"description":""}}]
```

Search recipients

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

const data = {
  list_id: -27497588,
  conditions: [
    {
      and_or: "",
      field: "birthday",
      value: "01/12/1985",
      operator: "eq",
    },
    {
      and_or: "",
      field: "birthday",
      value: "01/12/1985",
      operator: "eq",
    },
    {
      and_or: "",
      field: "birthday",
      value: "01/12/1985",
      operator: "eq",
    },
    {
      and_or: "",
      field: "birthday",
      value: "01/12/1985",
      operator: "eq",
    },
  ],
};

const request = {
  url: `/v3/contactdb/recipients/search`,
  method: "POST",
  body: data,
};

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"))

data = {
    "list_id": -27497588,
    "conditions": [
        {
            "and_or": "",
            "field": "birthday",
            "value": "01/12/1985",
            "operator": "eq",
        },
        {
            "and_or": "",
            "field": "birthday",
            "value": "01/12/1985",
            "operator": "eq",
        },
        {
            "and_or": "",
            "field": "birthday",
            "value": "01/12/1985",
            "operator": "eq",
        },
        {
            "and_or": "",
            "field": "birthday",
            "value": "01/12/1985",
            "operator": "eq",
        },
    ],
}

response = sg.client.contactdb.recipients.search.post(request_body=data)

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 data =
            @"{
            ""list_id"": -27497588,
            ""conditions"": [
                {
                    ""and_or"": """",
                    ""field"": ""birthday"",
                    ""value"": ""01/12/1985"",
                    ""operator"": ""eq""
                },
                {
                    ""and_or"": """",
                    ""field"": ""birthday"",
                    ""value"": ""01/12/1985"",
                    ""operator"": ""eq""
                },
                {
                    ""and_or"": """",
                    ""field"": ""birthday"",
                    ""value"": ""01/12/1985"",
                    ""operator"": ""eq""
                },
                {
                    ""and_or"": """",
                    ""field"": ""birthday"",
                    ""value"": ""01/12/1985"",
                    ""operator"": ""eq""
                }
            ]
        }";

        var response = await client.RequestAsync(
            method: SendGridClient.Method.POST,
            urlPath: "contactdb/recipients/search",
            requestBody: data);

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

```java
import com.sendgrid.*;
import java.io.IOException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Arrays;

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.POST);
            request.setEndpoint("/contactdb/recipients/search");
            request.setBody(new JSONObject(new HashMap<String, Object>() {
                {
                    put("list_id", -27497588);
                    put("conditions",
                        Arrays.asList(
                            new HashMap<String, Object>() {
                                {
                                    put("and_or", "");
                                    put("field", "birthday");
                                    put("value", "01/12/1985");
                                    put("operator", "eq");
                                }
                            },
                            new HashMap<String, Object>() {
                                {
                                    put("and_or", "");
                                    put("field", "birthday");
                                    put("value", "01/12/1985");
                                    put("operator", "eq");
                                }
                            },
                            new HashMap<String, Object>() {
                                {
                                    put("and_or", "");
                                    put("field", "birthday");
                                    put("value", "01/12/1985");
                                    put("operator", "eq");
                                }
                            },
                            new HashMap<String, Object>() {
                                {
                                    put("and_or", "");
                                    put("field", "birthday");
                                    put("value", "01/12/1985");
                                    put("operator", "eq");
                                }
                            }));
                }
            }).toString());
            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/contactdb/recipients/search", host)
	request.Method = "POST"
	request.Body = []byte(`{
  "list_id": -27497588,
  "conditions": [
    {
      "and_or": "",
      "field": "birthday",
      "value": "01/12/1985",
      "operator": "eq"
    },
    {
      "and_or": "",
      "field": "birthday",
      "value": "01/12/1985",
      "operator": "eq"
    },
    {
      "and_or": "",
      "field": "birthday",
      "value": "01/12/1985",
      "operator": "eq"
    },
    {
      "and_or": "",
      "field": "birthday",
      "value": "01/12/1985",
      "operator": "eq"
    }
  ]
}`)
	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);
$request_body = json_decode('{
    "list_id": -27497588,
    "conditions": [
        {
            "and_or": "",
            "field": "birthday",
            "value": "01/12/1985",
            "operator": "eq"
        },
        {
            "and_or": "",
            "field": "birthday",
            "value": "01/12/1985",
            "operator": "eq"
        },
        {
            "and_or": "",
            "field": "birthday",
            "value": "01/12/1985",
            "operator": "eq"
        },
        {
            "and_or": "",
            "field": "birthday",
            "value": "01/12/1985",
            "operator": "eq"
        }
    ]
}');

try {
    $response = $sg->client
        ->contactdb()
        ->recipients()
        ->search()
        ->post($request_body);
    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'])
data = JSON.parse('{
  "list_id": -27497588,
  "conditions": [
    {
      "and_or": "",
      "field": "birthday",
      "value": "01/12/1985",
      "operator": "eq"
    },
    {
      "and_or": "",
      "field": "birthday",
      "value": "01/12/1985",
      "operator": "eq"
    },
    {
      "and_or": "",
      "field": "birthday",
      "value": "01/12/1985",
      "operator": "eq"
    },
    {
      "and_or": "",
      "field": "birthday",
      "value": "01/12/1985",
      "operator": "eq"
    }
  ]
}')

response = sg.client.contactdb.recipients.search.post(request_body: data)
puts response.status_code
puts response.headers
puts response.body
```

```bash
curl -X POST "https://api.sendgrid.com/v3/contactdb/recipients/search" \
--header "Authorization: Bearer $SENDGRID_API_KEY" \
--header "Content-Type: application/json" \
--data '{"list_id": -27497588, "conditions": [{"and_or": "", "field": "birthday", "value": "01/12/1985", "operator": "eq"}, {"and_or": "", "field": "birthday", "value": "01/12/1985", "operator": "eq"}, {"and_or": "", "field": "birthday", "value": "01/12/1985", "operator": "eq"}, {"and_or": "", "field": "birthday", "value": "01/12/1985", "operator": "eq"}]}'
```
