# Refresh Segment

## API Overview

Segments are similar to contact lists, except they update dynamically over time as information stored about your contacts or the criteria used to define your segments changes. When you segment your audience, you are able to create personalized Automation emails and Single Sends that directly address the wants and needs of your particular audience.

The Marketing Campaigns Segments V2 API allows you to create, edit, and delete segments as well as retrieve a list of segments or an individual segment by ID.

Segments built using engagement data such as "was sent" or "clicked" will take approximately 30 minutes to begin populating.

Segment samples and counts refresh on a schedule that ranges from 1 to 24 hours. Segments with active automations or that are used as exclusion lists for scheduled Single Sends refresh every hour. Segments that aren't actively used refresh less frequently, up to every 24 hours, to optimize processing resources. Samples and counts displayed in the UI don't update immediately when segment criteria are modified or when contacts are added or updated. Instead, they update according to the segment's refresh schedule.

The Refresh Segment operation allows customers with [Marketing Campaigns Basic or Advanced plans](https://sendgrid.com/pricing/) to manually refresh segments. You can refresh a segment twice per day. Refreshes will be reset at midnight in the timezone stored for the segment. A segment cannot be refreshed more than once within one hour, and the endpoint has a rate limit of 10 requests per day that is reset at 0:00 UTC. Manually refreshing a segment does not affect the segment's backoff.

## Operation overview

```json
{"path":"https://api.sendgrid.com/v3/marketing/segments/2.0/refresh/{segment_id}","method":"post","servers":[{"url":"https://api.sendgrid.com","description":"The Twilio SendGrid v3 API"}]}
```

Manually refresh a segment by segment ID.

## 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":"segment_id","in":"path","required":true,"schema":{"type":"string","maxLength":36,"minLength":36,"format":"uuid"}}]
```

### Request body

```json
{"schema":{"title":"segment_refresh_request","required":["user_time_zone"],"type":"object","example":{"user_time_zone":"America/Chicago"},"refName":"SegmentRefreshRequest","modelName":"SegmentRefreshRequest","properties":{"user_time_zone":{"type":"string","description":"The user's timezone. The timezone is used to reset the refresh count at midnight in the user's local time. Only [IANA time zone format](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) is accepted."}}},"encodingType":"application/json"}
```

### Responses

```json
[{"responseCode":"202","schema":{"description":"The refresh was accepted and a request was sent to process.","content":{"application/json":{"schema":{"title":"segment_refresh_response","type":"object","example":{"job_id":"1588e03b-50aa-454a-97d1-e1530345a5ec"},"refName":"SegmentRefresh202","modelName":"SegmentRefresh202","properties":{"job_id":{"type":"string","description":"The ID of the manual refresh job. Used only for internal purposes."}}},"example":{"job_id":"1588e03b-50aa-454a-97d1-e1530345a5ec"}}}}},{"responseCode":"403","schema":{"description":"Endpoint is forbidden to the user because they are a free user."}},{"responseCode":"404","schema":{"description":"Segment ID was not found","content":{"application/json":{"schema":{"title":"error","required":["error"],"type":"object","refName":"SegmentError","modelName":"SegmentError","properties":{"error":{"type":"string","description":"A description of the error."}}},"example":{"error":"Segment does not exist."}}}}},{"responseCode":"429","schema":{"description":"The user has reached their limit of 2 requests per segment per day, 1 request per segment per hour, or 10 requests across all segments per day."}},{"responseCode":"500","schema":{"description":"","content":{"application/json":{"schema":{"title":"error","required":["error"],"type":"object","refName":"SegmentError","modelName":"SegmentError","properties":{"error":{"type":"string","description":"A description of the error."}}},"example":{"error":"Please check [our status page](https://status.sendgrid.com/) for updates or [contact support](https://support.sendgrid.com/) if the issue is not listed."}}}}}]
```

Manually refresh a segment

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

const segment_id = "f15982c1-a82c-4e87-a6b2-a4a63b4b7644";
const data = {
  user_time_zone: "America/Chicago",
};

const request = {
  url: `/v3/marketing/segments/2.0/refresh/${segment_id}`,
  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"))

segment_id = "f15982c1-a82c-4e87-a6b2-a4a63b4b7644"
data = {"user_time_zone": "America/Chicago"}

response = sg.client._(f"marketing/segments/2.0/refresh/{segment_id}").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 segmentId = "f15982c1-a82c-4e87-a6b2-a4a63b4b7644";
        var data =
            @"{
            ""user_time_zone"": ""America/Chicago""
        }";

        var response = await client.RequestAsync(
            method: SendGridClient.Method.POST,
            urlPath: $"marketing/segments/2.0/refresh/{segmentId}",
            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;

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("/marketing/segments/2.0/refresh/f15982c1-a82c-4e87-a6b2-a4a63b4b7644");
            request.setBody(new JSONObject(new HashMap<String, Object>() {
                {
                    put("user_time_zone", "America/Chicago");
                }
            }).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/marketing/segments/2.0/refresh/f15982c1-a82c-4e87-a6b2-a4a63b4b7644", host)
	request.Method = "POST"
	request.Body = []byte(`{
  "user_time_zone": "America/Chicago"
}`)
	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('{
    "user_time_zone": "America/Chicago"
}');
$segment_id = "f15982c1-a82c-4e87-a6b2-a4a63b4b7644";

try {
    $response = $sg->client
        ->_("marketing/segments/2.0/refresh/{$segment_id}")
        ->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('{
  "user_time_zone": "America/Chicago"
}')
segment_id = "f15982c1-a82c-4e87-a6b2-a4a63b4b7644"

response = sg.client._("marketing/segments/2.0/refresh/#{segment_id}").post(request_body: data)
puts response.status_code
puts response.headers
puts response.body
```

```bash
curl -X POST "https://api.sendgrid.com/v3/marketing/segments/2.0/refresh/f15982c1-a82c-4e87-a6b2-a4a63b4b7644" \
--header "Authorization: Bearer $SENDGRID_API_KEY" \
--header "Content-Type: application/json" \
--data '{"user_time_zone": "America/Chicago"}'
```
