# Get availability

> **POST** `https://api.us.nylas.com/v3/calendars/availability`

Source: https://developer.nylas.com/docs/reference/api/calendar/post-availability/

Returns availability information for the specified user or group of users. All participants' email
addresses must be associated with valid Nylas grants, and should be unique within their application.

**Authentication:** NYLAS_API_KEY, ACCESS_TOKEN

## Request body

Content-Type: application/json

- `availability_rules` (object)
  - `availability_method` (string)
  - `buffer` (object) - The amount of buffer time Nylas adds around existing meetings, in minutes. For example, if an
account has a meeting scheduled from 10:00–11:00a.m., and you set a buffer of 30 minutes, Nylas
treats 9:30–11:30a.m. as busy.
    - `before` (integer) - The amount of buffer time to add before meetings, in increments of five minutes. For example,
if an account has a meeting scheduled from 10:00–11:00a.m., and you set a `before` buffer of
30 minutes, Nylas treats 9:30–11:00a.m. as busy.

This value must be between 0 and 120, and must be divisible by 5.
    - `after` (integer) - The amount of buffer time to add after meetings, in increments of five minutes. For example, if
an account has a meeting scheduled from 10:00–11:00a.m., and you set an `after` buffer of 15
minutes, Nylas treats 10:00–11:15a.m. as busy.

This value must be between 0 and 120, and must be divisible by 5.
  - `default_open_hours` (array) - A default set of open hours to apply to all participants. You can overwrite these open hours for
individual participants by specifying `open_hours` on the Participant object.
    - `days` (array) - The days of the week that the open hours settings are applied to. Sunday corresponds to `0`, and
Saturday corresponds to `6`.
    - `timezone` (string) - The calendar's time zone as an [IANA-formatted](https://en.wikipedia.org/wiki/Tz_database) string.
    - `start` (string) - The start time for the open hours settings, in 24-hour time format. Nylas omits leading zeroes.

The minimum start time is `0:00`, and the maximum is `23:49`.
    - `end` (string) - The end time for the open hours settings, in 24-hour time format. Nylas omits leading zeroes.
    - `exdates` (array) - A list of dates that Nylas excludes from the account's open hours, in `YYYY-MM-DD` format.
  - `round_robin_group_id` (string) - The ID on events that Nylas considers when calculating the order of round-robin participants.
This is used for both max-fairness and max-availability calculations.

To calculate participant order correctly, set the metadata key `key5` to the same value on any
events you want to consider for the current set of round-robin participants. You can set this
key to any value that helps you identify events used to calculate availability in this group
(for example, `new_subscriber_onboarding`).
  - `tentative_as_busy` (boolean) - (Microsoft and EWS only) When `true`, Nylas treats tentative events as busy.
- `duration_minutes` (integer) **(required)** - The duration of each time slot, in minutes. The duration must be a multiple of 5
minutes.
- `end_time` (integer) **(required)** - The end of the time slot that Nylas checks availability for, in seconds using the Unix
timestamp format. The time must be a multiple of 5 minutes.
- `interval_minutes` (integer) - Nylas generates a time slot every `interval_minutes` (for example, every 30 minutes)
and returns only slots when all participants are free. The interval must be a multiple
of 5 minutes.
- `participants` (array) **(required)** - A list of participants to get availability information for.
  - `calendar_ids` (array) - A list of calendar IDs associated with the participant's email address. If not
defined, Nylas uses the participant's primary calendar ID.
  - `email` (string) - The participant's email address. The email address must be associated with a valid
Nylas grant, and should be unique within its application.
  - `grant_id` (string) - The participant's Nylas grant ID.
  - `open_hours` (array) - An array of the participant's open hours. Nylas searches for free time slots
within these hours.
    - `days` (array) - The days of the week that the open hours settings are applied to. Sunday corresponds to `0`, and
Saturday corresponds to `6`.
    - `timezone` (string) - The calendar's time zone as an [IANA-formatted](https://en.wikipedia.org/wiki/Tz_database) string.
    - `start` (string) - The start time for the open hours settings, in 24-hour time format. Nylas omits leading zeroes.

The minimum start time is `0:00`, and the maximum is `23:49`.
    - `end` (string) - The end time for the open hours settings, in 24-hour time format. Nylas omits leading zeroes.
    - `exdates` (array) - A list of dates that Nylas excludes from the account's open hours, in `YYYY-MM-DD` format.
  - `only_specific_time_availability` (boolean) - When `true`, Nylas checks availability only against this participant's
`specific_time_availability` entries and ignores their regular `open_hours`.
  - `specific_time_availability` (array) - An array of date and time ranges when the participant is available. Use with
`only_specific_time_availability` set to `true` to restrict availability
to only these windows.
    - `date` (string) **(required)** - The date in `YYYY-MM-DD` format.
    - `end` (string) **(required)** - The end time in `HH:MM` format (24-hour).
    - `start` (string) **(required)** - The start time in `HH:MM` format (24-hour).
    - `timezone` (string) **(required)** - The participant's IANA timezone for this availability window.
- `round_to` (integer) - Nylas rounds each time slot to the nearest `round_to` value. For example, if a time
slot starts at 9:05a.m. and `round_to` is set to `15`, Nylas rounds it to 9:15a.m. The
round to value must be a multiple of 5 minutes.
- `start_time` (integer) **(required)** - The beginning of the time slot that Nylas checks availability for, in seconds using
the Unix timestamp format. The time must be a multiple of 5 minutes.

## Responses

### 200 - Return availability

- `request_id` (string) - The request ID.
- `data` (object) - The response to a successful request to get availability for a participant.
  - `order` (array) - (Round-robin events only) The order of participants in line to attend the proposed meeting.
  - `time_slots` (array,null) - An array of the available time slots when you can create a meeting using the requested settings.
This field may be `null` if no time slots are available. Treat `null` the same as an empty array.

### 400 - Bad Request

- `request_id` (string) - The request ID.
- `error` (object) - The response error object.
  - `type` (string) - The error type.
  - `message` (string) - The error message.
  - `provider_error` (object) - The error from the provider.

### 401 - Unauthorized

- `request_id` (string) - The request ID.
- `error` (object) - The response error object.
  - `type` (string) - The error type.
  - `message` (string) - The error message.
  - `provider_error` (object) - The error from the provider.

### 429 - Rate Limit

- `request_id` (string) - The request ID.
- `error` (object) - The response error object.
  - `type` (string) - The error type.
  - `message` (string) - The error message.

### 504 - Provider Failure

- `request_id` (string) - The request ID.
- `error` (object) - The response error object.
  - `type` (string) - The error type.
  - `message` (string) - The error message.

## Code samples

### cURL

```bash
curl --compressed --request POST \
	--url 'https://api.us.nylas.com/v3/calendars/availability' \
	--header 'Accept: application/json' \
	--header 'Authorization: Bearer <NYLAS_API_KEY>' \
	--header 'Content-Type: application/json' \
	--data '{
		"participants": [
			{
				"email": "leyah@example.com",
				"calendar_ids": ["leyah@example.com"],
				"open_hours": [{
					"days": [0,1,2],
					"timezone": "America/Toronto",
					"start": "9:00",
					"end": "17:00",
					"exdates": []
				}]
			},
			{
				"email": "nyla@example.com",
			}
		],
		"start_time": 1600890600,
		"end_time": 1600999200,
		"interval_minutes": 30,
		"duration_minutes": 30,
		"round_to": 15,
		"availability_rules": {
			"availability_method": "collective",
			"buffer": {
				"before": 15,
				"after": 15
			},
			"default_open_hours": [
				{
					"days": [0,1,2],
					"timezone": "America/Toronto",
					"start": "9:00",
					"end": "17:00",
					"exdates": []
				},
				{
					"days": [3,4,5],
					"timezone": "America/Toronto",
					"start": "10:00",
					"end": "18:00",
					"exdates": []
				}
			]
		}
	}'
```

### Node.js SDK

```javascript
import Nylas from "nylas";

const nylas = new Nylas({
  apiKey: "<NYLAS_API_KEY>",
  apiUri: "<NYLAS_API_URI>",
});

const email = "<EMAIL>";

async function getCalendarAvailability() {
  try {
    const calendar = await nylas.calendars.getAvailability({
      requestBody: {
        startTime: 1630435200,
        endTime: 1630521600,
        durationMinutes: 15,
        participants: [{ email }],
      },
    });

    console.log("Calendar:", calendar);
  } catch (error) {
    console.error("Error to create calendar:", error);
  }
}

getCalendarAvailability();

```

### Python SDK

```python
from nylas import Client

nylas = Client(
    "<NYLAS_API_KEY>",
    "<NYLAS_API_URI>"
)

grant_id = "<NYLAS_GRANT_ID>"
email = "<EMAIL>"

availability = nylas.calendars.get_availability(
  request_body={
    "start_time": 1630435200,
    "end_time": 1630521600,
    "duration_minutes": 15,
    "participants": [{"email": email}]
  }
)

print(availability)
```

### Ruby SDK

```ruby
# Load gems
require 'nylas'
require 'date'

# Initialize Nylas client
nylas = Nylas::Client.new(
		api_key: "<NYLAS_API_KEY>"
)

# Get today’s date
today = Date.today

# When do we start and end searching for availability
start_time = Time.local(today.year, today.month, today.day, 8, 0,0).strftime("%s").to_i
end_time = Time.local(today.year, today.month, today.day, 17, 0,0).strftime("%s").to_i

# Body of our request
request_body = {
	"participants": [{
		"email": "<NYLAS_GRANT_ID>",
		"calendar_ids": [
			"<CALENDAR_ID>"
		],
	}],
	"start_time": start_time,
	"end_time": end_time,
	"duration_minutes": 60,
}

# Call the get_availability endpoint
available, _request_ids = nylas.calendars.get_availability(request_body: request_body)

# Display available spots
available[:time_slots].each {|slots|
	puts "From: #{Time.at(slots[:start_time]).to_datetime.strftime("%H:%M:%S")}" \
	     " To: #{Time.at(slots[:end_time]).to_datetime.strftime("%H:%M:%S")}"
}
```

### Java SDK

```java
// Import Nylas packages
import com.nylas.NylasClient;
import com.nylas.models.*;

import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.text.SimpleDateFormat;

public class get_availability {
  public static void main(String[] args) throws NylasSdkTimeoutError, NylasApiError {
    NylasClient nylas = new NylasClient.Builder("<NYLAS_API_KEY>").build();
    
    // Get today's date
    LocalDate today = LocalDate.now();
    // Our day starts at 8:00am
    Instant sixPmUtc = today.atTime(13, 0).toInstant(ZoneOffset.UTC);
    // Get time as a Unix timestamp
    long startTime = sixPmUtc.getEpochSecond();
    // Add 9 hours, so our day ends at 5:00pm
    Instant sixPmUtcPlus = sixPmUtc.plus(9, ChronoUnit.HOURS);
    long endTime = sixPmUtcPlus.getEpochSecond();

    List<String> calendars = new ArrayList<>();
    calendars.add("<CALENDAR_ID>");

    AvailabilityParticipant participant = new AvailabilityParticipant.Builder("<PARTICIPANT_EMAIL>")
        .calendarIds(calendars)
        .build();
    List<AvailabilityParticipant> participants = new ArrayList<>();
    participants.add(participant);

    GetAvailabilityRequest availability = new GetAvailabilityRequest.Builder(
        Math.toIntExact(startTime),
        Math.toIntExact(endTime),
        participants,
        60).build();

    Response<GetAvailabilityResponse> available = nylas.calendars().getAvailability(availability);

    assert available.getData().getTimeSlots() != null;

    for(TimeSlot times : available.getData().getTimeSlots()){
        String initDate = new SimpleDateFormat("HH:mm:ss").
        format(new java.util.Date((times.getStartTime() * 1000L)));
        String endDate = new SimpleDateFormat("HH:mm:ss").
        format(new java.util.Date((times.getEndTime() * 1000L)));
        
        System.out.println("From " + initDate + " To: " + endDate);
    }
  }
}
```

### Kotlin SDK

```kotlin
// Import Nylas packages
import com.nylas.NylasClient
import com.nylas.models.*

// Import Java Packages
import java.text.SimpleDateFormat
import java.time.LocalDateTime
import java.time.ZoneOffset

fun main(args: Array<String>) {
  // Initialize Nylas client
  val nylas: NylasClient = NylasClient(
      apiKey = "<NYLAS_API_KEY>"
  )

  // Get today's day
  var startDate = LocalDateTime.now()

  // Set time. As we're using UTC we need to add the hours in difference
  // from our own Timezone
  startDate = startDate.withHour(12);
  startDate = startDate.withMinute(0);
  startDate = startDate.withSecond(0);
  val endDate = startDate.withHour(21);

  val calendars : List<String> = listOf("<CALENDAR_ID>")
  val participant = AvailabilityParticipant("<NYLAS_GRANT_ID>", calendars, null)
  val participants : List<AvailabilityParticipant> = listOf(participant)

  val request = GetAvailabilityRequest(startDate.toEpochSecond(ZoneOffset.UTC).toInt(),
      endDate.toEpochSecond(ZoneOffset.UTC).toInt(), participants, 60)

  val available : Response<GetAvailabilityResponse> = nylas.calendars().
      getAvailability(request)

  for(slot in available.data.timeSlots!!){
    println("From: " + SimpleDateFormat("HH:mm:ss").format((slot.startTime * 1000L)) +
        " to: " + SimpleDateFormat("HH:mm:ss").format((slot.endTime * 1000L)))
  }
}
```
