The developers'

API Guide

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

How do APIs work?

As explained in our earlier article “What is an API,” an API enables seamless communication between software applications, facilitating data exchange and integration without users needing to understand the underlying code. But how does it work? Let’s dive into the mechanics of APIs and explore how they function to make this essential aspect of modern software development possible.

API components

API components play a crucial role in how API works and are essential for enabling communication and interaction between different applications and systems. These components form the backbone of API functionality, each with its distinct purpose and functionality. 

Here is the list of API components:

API endpoints: 

API endpoints, as a fundamental API component, are specific URLs or URIs (Uniform Resource Identifiers) within an API that serve as access points to interact with various functionalities or resources the API provides. Each endpoint is designed to perform a specific operation or retrieve a particular data set from the API.

Endpoints act as the “doors” or “paths” through which a client application can send HTTP requests to the API server. These requests typically use HTTP methods such as GET (retrieve data), POST (create new data), PUT (update existing data), or DELETE (remove data) to perform actions or retrieve information.

For example, in a Calendar API, you might have different endpoints like:

  • /calendars: To retrieve all of a user’s available calendars for a user
  • /events: To fetch all of a user’s events from a calendar

API endpoints define the available functions and resources within the API, allowing developers to access and manipulate data or trigger specific actions programmatically. 

API requests

The “Request” component of an API refers to the action taken by a client application to initiate communication with the API server. It involves sending an HTTP request to a specific API endpoint to request data or perform a specific operation. The key request methods that define the actions you can perform on an API’s endpoints are – GET, POST, PUT, and DELETE. 

Every API request begins with selecting an appropriate HTTP method (or an HTTP verb). Here’s an in-depth look at HTTP methods:

  • GET: The GET method is used to retrieve data from the server. When a client sends a GET request, it asks the server to provide the resource specified by the URL. GET requests are read-only and should not have any side effects on the server. They are commonly used for fetching information, such as reading an article or retrieving user profiles.
  • POST: POST is employed to create new data on the server. When a client sends a POST request, it submits data to the server, typically in the request body. The server processes this data and may create a new resource. POST requests can be used to create a new user account, add a comment to a post, or submit a form.
  • PUT: PUT is used to update existing data on the server. Clients send PUT requests to specify the resource’s URL and provide the updated data in the request body. The server then replaces or updates the resource with the new information. PUT requests are idempotent, meaning that multiple identical requests will have the same effect as a single request, ensuring consistency.
  • DELETE: The DELETE method removes data or resources from the server. Clients send DELETE requests with the URL of the resource to be deleted. Upon receiving such a request, the server performs the deletion operation. DELETE requests should also be idempotent, allowing multiple requests to result in the same state.

These HTTP methods form the core of API interactions, allowing clients to perform various actions, from retrieving information and creating new records to updating and deleting existing data. Proper utilization of these methods is essential for designing RESTful (Representational State Transfer) APIs, which adhere to simplicity, scalability, and statelessness principles. 

When working with APIs, developers must choose the appropriate HTTP method to accurately convey the intended operation and ensure the desired outcome on the server.

API response

An API’s “Response” component refers to the data or information sent back by the API server after processing a request. It plays a critical role in communicating between client applications and the API. 

Here are key details about the Response component:

  • Format: API responses are typically formatted in a structured way to facilitate data exchange between the client and server. Depending on the API’s design and purpose, common formats include JSON (JavaScript Object Notation), XML (eXtensible Markup Language), HTML, or even plain text. JSON is widely favored for its simplicity and ease of parsing in modern web applications.
  • HTTP status codes: Responses include an HTTP status code, which indicates the outcome of the request. Common HTTP status codes include:
    • 200 OK: The request was successful, and the server is returning the requested data.
    • 201 Created: The request has resulted in creating a new resource on the server.
    • 204 No Content: The request was successful, but there is no data to return.
    • 400 Bad request: The client’s request is malformed or contains errors.
    • 401 Unauthorized: Authentication credentials are missing or invalid.
    • 403 Forbidden: The client is not allowed to access the requested resource.
    • 404 Not found: The requested resource does not exist.
    • 500 Internal server error: An unexpected server error occurred.
  • Data payload: The response may contain a data payload that includes the information or resources requested by the client. This data is typically encoded in the chosen format (e.g., JSON) and can vary in complexity from a single value to a complex object with nested data structures.
  • Headers: In addition to the data payload, API responses include HTTP headers that provide metadata about the response, such as the content type, content length, and caching instructions. Headers are essential for both interpreting the response and optimizing client-side processing.
  • Pagination: In cases where an API resource may have a large amount of data, responses often include pagination information. This helps clients retrieve data in manageable chunks by providing links or metadata for navigating multiple results pages.
  • Error handling: API responses also include information about errors that may have occurred during the request. This typically consists of an error code, a human-readable error message, and, in some cases, additional details to assist developers in diagnosing and fixing issues.
  • Rate-limiting information: Some APIs include headers that convey rate-limiting information to clients. This informs developers about the maximum number of requests allowed within a specified time frame, helping them manage their API usage and avoid hitting rate limits.
  • Conditional responses: Advanced APIs may support conditional requests and responses. In such cases, the client can include conditional headers (e.g., If-Modified-Since) in the request to check if a resource has been modified for a certain time. The server can then respond with a 304 Not Modified status code if the resource hasn’t changed, saving bandwidth and processing time.
  • Authentication: Authentication mechanisms, such as API keys, OAuth tokens, or JWTs, ensure that only authorized users or applications can access the API. This is crucial for security and protecting sensitive data.
  • Request and response formats (JSON, XML, etc.): APIs typically use standardized formats like JSON or XML to structure data in requests and responses. JSON is the most commonly used due to its simplicity and readability. The importance is in ensuring a common data structure for seamless data exchange.
  • Status codes: HTTP status codes (e.g., 200 OK, 404 Not Found) provide information about the outcome of an API request. They help clients understand whether their request was successful or whether they encountered an issue.
  • Error handling: Robust error handling mechanisms ensure that the API provides meaningful error messages when something goes wrong to help developers diagnose and resolve issues quickly.
  • Webhooks: Webhooks enable real-time notifications from the API to a client when certain events occur. They are crucial for building event-driven applications and keeping data up to date.
  • Security: API security involves measures like encryption (HTTPS), input validation, and access controls to protect against data breaches and unauthorized access.
  • Monitoring and analytics: Tools for monitoring API usage and performance are essential for tracking the health of the API, identifying bottlenecks, and optimizing it over time.
  • Documentation: Comprehensive documentation is vital for developers to understand how to use the API effectively. It should include details about endpoints, authentication, request/response formats, and example usage. Think of it as the user manual for your API.

Authentication

APIs often require authentication to ensure only authorized users or applications can access their data or services. This can involve API keys, OAuth tokens, or other authentication mechanisms. Learn more about Authentication and Authorization

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": "anna.molly@example.com",
      "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": "6aaaaaaame8kpgcid6hvd0q@google.com",
    "id": "6aaaaaaame8kpgcid6hvd",
    "object": "event",
    "organizer": {
      "email": "anna.molly@example.com",
      "name": ""
    },
    "participants": [
      {
        "email": "jenna.doe@example.com",
        "status": "yes"
      },
      {
        "email": "anna.molly@example.com",
        "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": "anna.molly@example.com",
      "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": "6aaaaaaame8kpgcid6hvd0q@google.com",
    "id": "6aaaaaaame8kpgcid6hvd",
    "object": "event",
    "organizer": {
      "email": "anna.molly@example.com",
      "name": ""
    },
    "participants": [
      {
        "email": "jenna.doe@example.com",
        "status": "yes"
      },
      {
        "email": "anna.molly@example.com",
        "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.

How to integrate with an API?

Integrating with an API opens up a world of possibilities for enhancing your applications with external data and services. Whether you’re building a website, a mobile app, or a backend system, understanding the step-by-step process outlined above is essential. It enables you to harness the power of APIs to retrieve data, automate tasks, and offer valuable features to your users.

Ready to dive deeper into the world of API integration? Explore our comprehensive guide on API integration, where you’ll find in-depth information, best practices, and real-world examples to help you master the art of seamless API integration. Discover how APIs can transform your applications and elevate your user experience.

How to create an API

Creating an API is fundamental in opening up your software or services to external developers and applications. Whether you want to share data, functionality, or services, having a well-designed and accessible API is key to seamless integration. Below, we’ll take you through the basic steps to create an API from start to finish. From defining your objectives to deploying and maintaining your API, we’ll cover the essential aspects of API development. 

Build vs Buy guide

Building your API from scratch or purchasing an existing solution is a critical decision in your API development journey. To help you make an informed choice, we’ve prepared a comprehensive guide outlining each approach’s advantages and drawbacks.

Step 1. Define your objectives:

Start by clearly defining the objectives of your API. What data or functionality do you want to expose to external developers or applications? Understanding your goals is crucial for designing a well-structured API.

Step 2. Choose a protocol:

Select a communication protocol for your API. The most common choice is HTTP/HTTPS due to its simplicity and wide support. Decide whether you’ll use REST (Representational State Transfer), GraphQL, or another protocol that suits your needs.

Step 3. Design your API:

Design the structure of your API by defining endpoints and the data they will provide. Consider the needs of your potential users and create a logical hierarchy for your API resources.

Step 4. Authentication and authorization:

Determine how you will handle authentication and authorization. Decide whether you’ll use API keys, OAuth, token-based authentication, or other methods to secure access to your API.

Step 5. Data format:

Choose a data format for your API responses. JSON and XML are common choices. Ensure that your API provides consistent and well-documented data structures.

Step 6. Create endpoints:

Implement the API endpoints based on your design. Each endpoint represents a specific resource or functionality. Code the logic that fulfills the requests to these endpoints.

Step 7. Request handling:

Define how your API handles incoming requests. Specify how parameters, headers, and request bodies are processed to deliver the requested data or perform actions.

Step 8. Response handling:

Implement response handling to format the data and provide appropriate HTTP status codes. Ensure that your API returns informative error messages in case of issues.

Step 9. Testing:

Thoroughly test your API to ensure it works as expected. Use testing tools like Postman or automated testing frameworks to verify functionality, security, and performance.

Step 10. Documentation:

Create comprehensive API documentation. Include information about endpoints, request parameters, response structures, and authentication. Clear documentation is crucial for developers who will use your API.

Step 11. Versioning:

Plan for versioning your API to accommodate future changes or enhancements without breaking existing integrations. Use version numbers in your API URLs or headers.

Step 12. Security:

Implement security best practices to protect your API from potential threats. This includes input validation, rate limiting, and securing sensitive data.

Step 13. Monitoring and analytics:

Set up monitoring and analytics tools to track API usage, detect issues, and gain insights into how your API is performing.

Step 14. Deployment:

Deploy your API to a production environment, ensuring it’s accessible to external users or applications. Consider scalability and redundancy for high availability.

Step 14. Promotion:

Promote your API to developers and potential users. Provide clear onboarding instructions, showcase use cases, and offer support channels for assistance.

Step 14. Maintenance and updates:

Regularly maintain and update your API to address issues, add new features, or improve performance. Communicate changes to your users through release notes and versioning.

By following these steps, you can create a well-designed and functional API that provides value to your users and encourages adoption by external developers and applications. Keep your API documentation current and be responsive to user feedback to foster a successful API ecosystem.

Not sure if to “Build or Buy”?  Download the Build vs Buy Guide