The developers'

API Guide

Everything you need to know about building, purchasing and integrating with APIs.

How to use an API: A step-by-step process

This step-by-step process demonstrates how APIs work by enabling client applications to communicate with remote servers, retrieve data, and integrate it into various applications. The specifics of the process may vary depending on the API’s design and authentication requirements, but the fundamental steps remain consistent.

Step 1. Identify the API

Begin by identifying the specific API you want to interact with. This could be an API for weather data, e-commerce products, social media posts, or any other programmable access service. 

Example: You want to use the Nylas Calendar API to retrieve all of a user’s calendars.

Step 2. Obtain API credentials

Many APIs require authentication for security and access control. Obtain the necessary credentials, such as API keys, tokens, or client IDs from the API provider. This typically involves registering for an account on the API provider’s website.

Example: You sign up for a Nylas account and receive an API key.

Step 3. Choose an endpoint:

Determine which specific endpoint of the API you need to use for your task. Each endpoint represents a different functionality or resource offered by the API.

Example: You choose the “Events” endpoint (“/events”) from the Nylas API to get all events from a specific calendar.

Step 4. Construct the request:

Create an HTTP request to the chosen API endpoint. Specify the following:

  • HTTP method: Typically, “GET” is used for retrieving data.
  • Endpoint URL: Combine the base API URL with the chosen endpoint.
  • API key: Include your API key in the request headers for authentication

Example:

GET https://api.us.nylas.com/v3/grants/<GRANT_ID>/events&calendar_id={{calendar_id}

Step 5. Send the request:

Use a programming language or an API client library to send the HTTP request to the API server.

Node.js

Ruby

Python

Java

Curl

Response

import 'dotenv/config'
import Nylas from 'nylas'

const NylasConfig = {
  apiKey: process.env.NYLAS_API_KEY,
  apiUri: process.env.NYLAS_API_URI
}

const nylas = new Nylas(NylasConfig)

async function fetchAllEventsFromCalendar() { 
  try {
    const events = await nylas.events.list({
      identifier: process.env.NYLAS_GRANT_ID,
      queryParams: {
        calendarId: process.env.NYLAS_CALENDAR_ID,
      }
    })
  
    console.log('Events:', events)
  } catch (error) {
    console.error('Error fetching calendars:', error)
  }
}

fetchAllEventsFromCalendar() 
require 'nylas'

nylas = Nylas::Client.new(api_key: "<API_KEY_OR_ACCESS_TOKEN>")
events, _request_ids = nylas.events.list(identifier: "<GRANT_ID>")   
from dotenv import load_dotenv
load_dotenv()

import os
import sys
from nylas import Client

nylas = Client(
    os.environ.get('NYLAS_API_KEY'),
    os.environ.get('NYLAS_API_URI')
)

grant_id = os.environ.get("GRANT_ID")

events = nylas.events.list(
    grant_id,
    query_params={
      "calendar_id": os.environ.get("CALENDAR_ID")
    }
)

print(events)   
import com.nylas.NylasClient;
import com.nylas.models.When;

import com.nylas.models.*;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Objects;

public class read_calendar_events {
  public static void main(String[] args) throws NylasSdkTimeoutError, NylasApiError {
    NylasClient nylas = new NylasClient.Builder("<NYLAS_API_KEY_OR_ACCESS_TOKEN>").build();

    // Build the query parameters to filter our the results
    ListEventQueryParams listEventQueryParams = new ListEventQueryParams.
        Builder("<NYLAS_CALENDAR_ID>").build();

    // Read the events from our main calendar
    List<Event> events = nylas.events().list("<NYLAS_GRANT_ID>", 
    listEventQueryParams).getData();

    // Loop the events
    for (Event event : events) {
      System.out.print("Id: " + event.getId() + " | ");
      System.out.print("Title: " + event.getTitle());

      // Dates are handled differently depending on the event type
      switch (Objects.requireNonNull(event.getWhen().getObject()).getValue()) {
        case "datespan" -> {
          When.Datespan date = (When.Datespan) event.getWhen();

          System.out.print(" | The date of the event is from: " + 
              date.getStartDate() + " to " + 
              date.getEndDate());
        }
        case "date" -> {
          When.Date date = (When.Date) event.getWhen();
          
          System.out.print(" | The date of the event is: " +date.getDate());
        }
        case "timespan" -> {
          When.Timespan timespan = (When.Timespan) event.getWhen();

          String initDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").
          format(new java.util.Date((timespan.getStartTime() * 1000L)));

          String endDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").
          format(new java.util.Date((timespan.getEndTime() * 1000L)));

          System.out.print(" | The time of the event is from: " + 
          initDate + " to " + endDate);
        }
      }

      System.out.print(" | Participants: ");

      for(Participant participant : event.getParticipants()){
          System.out.print(" Email: " + participant.getEmail() +
              " Name: " + participant.getName() +
              " Status: " + participant.getStatus());
      }

      System.out.println("\n");
    }
  }
}   
curl --request GET \
  --url https://api.us.nylas.com/v3/grants/<GRANT_ID>/events&calendar_id={{calendar_id}}
  --header 'Accept: application/json' \
  --header 'Authorization: Bearer <NYLAS_API_KEY_OR_ACCESS_TOKEN>' \
  --header 'Content-Type: application/json' 
{
  "request_id": "cbd60372-df33-41d3-b203-169ad5e3AAAA",
  "data": [{
    "busy": true,
    "calendar_id": "primary",
    "conferencing": {
      "details": {
        "meeting_code": "ist-****-tcz",
        "url": "https://meet.google.com/ist-****-tcz"
      },
      "provider": "Google Meet"
    },
    "created_at": 1701974804,
    "creator": {
      "email": "[email protected]",
      "name": ""
    },
    "description": null,
    "grant_id": "1e3288f6-124e-405d-a13a-635a2ee54eb2",
    "hide_participants": false,
    "html_link": "https://www.google.com/calendar/event?eid=NmE0dXIwabQAAAA",
    "ical_uid": "[email protected]",
    "id": "6aaaaaaame8kpgcid6hvd",
    "object": "event",
    "organizer": {
      "email": "[email protected]",
      "name": ""
    },
    "participants": [
      {
        "email": "[email protected]",
        "status": "yes"
      },
      {
        "email": "[email protected]",
        "status": "yes"
      }
    ],
    "read_only": true,
    "reminders": {
      "overrides": null,
      "use_default": true
    },
    "status": "confirmed",
    "title": "Holiday check in",
    "updated_at": 1701974915,
    "when": {
      "end_time": 1701978300,
      "end_timezone": "America/Los_Angeles",
      "object": "timespan",
      "start_time": 1701977400,
      "start_timezone": "America/Los_Angeles"
    }
  }]
}

Step 6. API processes the request:

The API server receives your request, processes it, and performs the requested action, such as retrieving weather data for New York.

Example: The OpenWeatherMap server processes your request and retrieves the current weather data for New York.

Receive and Process the Response:

The API server sends back an HTTP response, typically in JSON or XML format. Extract and process the data from the response.

{
  "request_id": "cbd60372-df33-41d3-b203-169ad5e3AAAA",
  "data": [{
    "busy": true,
    "calendar_id": "primary",
    "conferencing": {
      "details": {
        "meeting_code": "ist-****-tcz",
        "url": "https://meet.google.com/ist-****-tcz"
      },
      "provider": "Google Meet"
    },
    "created_at": 1701974804,
    "creator": {
      "email": "[email protected]",
      "name": ""
    },
    "description": null,
    "grant_id": "1e3288f6-124e-405d-a13a-635a2ee54eb2",
    "hide_participants": false,
    "html_link": "https://www.google.com/calendar/event?eid=NmE0dXIwabQAAAA",
    "ical_uid": "[email protected]",
    "id": "6aaaaaaame8kpgcid6hvd",
    "object": "event",
    "organizer": {
      "email": "[email protected]",
      "name": ""
    },
    "participants": [
      {
        "email": "[email protected]",
        "status": "yes"
      },
      {
        "email": "[email protected]",
        "status": "yes"
      }
    ],
    "read_only": true,
    "reminders": {
      "overrides": null,
      "use_default": true
    },
    "status": "confirmed",
    "title": "Holiday check in",
    "updated_at": 1701974915,
    "when": {
      "end_time": 1701978300,
      "end_timezone": "America/Los_Angeles",
      "object": "timespan",
      "start_time": 1701977400,
      "start_timezone": "America/Los_Angeles"
    }
  }]
}   

Process this JSON data to extract calendar events, event details, and other relevant information.

Step 7. Use the retrieved data:

Utilize the data obtained from the API response in your application. You can display it to users, perform further calculations, or integrate it into your business logic.

Example: Display the user’s daily agenda of events on a website or mobile app.

Step 8. Error Handling:

Implement error handling in cases where the API request fails or returns an error response. This ensures a graceful response to issues like network problems or invalid API key.

Example: If the API response has a non-200 HTTP status code, handle the error accordingly, such as notifying the user or retrying the request.