The developers'

API Guide

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

API authentication methods

Various methods are employed for API authentication, each with unique characteristics and levels of security. Choosing the right method depends on the specific requirements and context of the API, such as the sensitivity of the data, the expected user base, and the application environment.

Basic authentication 

This is one of the simplest forms of authentication. It involves sending a username and password with each API request, typically encoded in Base64. While easy to implement, it is less secure because credentials are sent with each request and can be intercepted if not transmitted over HTTPS.

  • Advantages:
    • Simplicity: Easy to implement and understand.
    • Wide support: Universally supported across various platforms and frameworks.
  • Disadvantages:
    • Security risks: Less secure, especially if not used over HTTPS, as credentials are sent with each request.
    • Vulnerability to attacks: Susceptible to interception and replay attacks.

Example: A simple cURL request using basic authentication to access an API endpoint:

curl -X GET \
  https://api.example.com/data \
  -H 'Authorization: Basic [Base64-encoded-username:password]'

In Python, using the requests library:

import requests
from requests.auth import HTTPBasicAuth

response = requests.get(
    'https://api.example.com/data',
    auth=HTTPBasicAuth('username', 'password')
)
print(response.json())

Token-based authentication

In this method, the user first sends their credentials to the server. Upon successful authentication, the server issues a token (like a JSON Web Token – JWT), which the client sends in the header of each subsequent request. This method is more secure than basic authentication as the credentials are not repeatedly sent over the network.

  • Advantages:
    • Enhanced security: Reduces the risk of credential exposure as tokens can be limited in scope and duration.
    • Statelessness: Ideal for scalable applications since the server doesn’t need to maintain a session state.
  • Disadvantages:
    • Token management: Requires secure management and storage of tokens.
    • Complexity: More complex to implement than basic authentication.

Example: A Python example using JWT:

First, the client authenticates and receives a token:

import requests

# Authenticate and receive a token
response = requests.post('https://api.example.com/authenticate', data={'username': 'user', 'password': 'pass'})
token = response.json()['token']

Then, the client uses this token in subsequent requests:

headers = {'Authorization': f'Bearer {token}'}
response = requests.get('https://api.example.com/data', headers=headers)
print(response.json())

Multi-factor authentication (MFA):

MFA requires users to provide two or more verification factors to gain access to the API. This could include something they know (password), something they have (a phone), or something they are (biometric verification). It is essential for high-security APIs, especially those handling sensitive personal or financial data. While MFA significantly enhances security, it can add complexity to the user experience. It’s important to balance security needs with usability.

  • Advantages:
    • Increased security: Significantly enhances security by adding layers of authentication.
    • Reduced fraud risk: This makes unauthorized access considerably more difficult.
  • Advantages:
    • User experience: This can complicate the login process, potentially impacting user experience.
    • Implementation complexity: More complex to implement and manage.

API keys

An API key is a unique identifier used to authenticate a client. It’s simpler than OAuth but less secure, as it doesn’t have built-in mechanisms for granular access control or token expiration. API keys are suitable for controlling access to public APIs or services where sensitive data is not involved.

  • Advantages:
    • Ease of use: Simple to implement and use, with minimal overhead.
    • Control access: Useful for controlling access to public APIs or less sensitive data.
  • Disadvantages:
    • Limited security: Less secure as API keys can be easily intercepted if not properly protected.
    • Inadequate for sensitive data: Not recommended for high-security environments.

Example of API Key authentication method

This code sample demonstrates how to authenticate API requests using an API key, a common method for securing access to web services.

Node.js

Ruby

Python

Java

Curl

Response

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

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

const nylas = new Nylas(config)

const connector = await nylas.connectors.create({
  requestBody: {
    settings: {
      clientId: process.env.GCP_CLIENT_ID,
      clientSecret: process.env.GCP_CLIENT_SECRET,
    },
    scope: [
      'openid',
      'https://www.googleapis.com/auth/userinfo.email',
      'https://www.googleapis.com/auth/gmail.modify',
      'https://www.googleapis.com/auth/calendar',
      'https://www.googleapis.com/auth/contacts',
    ],
  }
})   
require 'nylas'

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

request_body = {
  provider: "google",
  settings: {
    clientId: "<GCP_CLIENT_ID>",
    clientSecret: "<GCP_CLIENT_SECRET>",
  },
  scope: [
    'openid',
    'https://www.googleapis.com/auth/userinfo.email',
    'https://www.googleapis.com/auth/gmail.modify',
    'https://www.googleapis.com/auth/calendar',
    'https://www.googleapis.com/auth/contacts',
  ]
}

nylas.connectors.create(request_body: request_body)   
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')
)

# Create a connector
connector = nylas.connectors.create(
  request_body={
    "provider": "google",
    "settings": {
      "client_id": os.environ.get('GOOGLE_CLIENT_ID'),
      "client_secret": os.environ.get('GOOGLE_CLIENT_SECRET')
    },
    "scopes": [
      'openid',
      'https://www.googleapis.com/auth/userinfo.email',
      'https://www.googleapis.com/auth/gmail.modify',
      'https://www.googleapis.com/auth/calendar',
      'https://www.googleapis.com/auth/contacts'
    ]
  }
)   
import com.nylas.NylasClient;
import com.nylas.models.*;
import java.util.ArrayList;
import java.util.List;

public class connector {
  public static void main(String[] args) throws NylasSdkTimeoutError, NylasApiError {
    NylasClient nylas = new NylasClient.Builder("<NYLAS_API_KEY>").build();
    List<String> scope = new ArrayList<>();

    scope.add("openid");
    scope.add("https://www.googleapis.com/auth/userinfo.email");
    scope.add("https://www.googleapis.com/auth/gmail.modify");
    scope.add("https://www.googleapis.com/auth/calendar");
    scope.add("https://www.googleapis.com/auth/contacts");

    GoogleCreateConnectorSettings settings = new 
    GoogleCreateConnectorSettings("<GCP_CLIENT_ID>", "<GCP_CLIENT_SECRET>","");

    CreateConnectorRequest request = new 
    CreateConnectorRequest.Google(settings, scope);

    nylas.connectors().create(request);
  }
}   
{
  "name": "Staging App 1",
  "provider": "microsoft",
  "settings": {
    "client_id": "abc-def",
    "tenant": "common"
  },
  "scope": [
    "Mail.Read",
    "User.Read",
    "offline_access"
  ]
}   
{
  "name": "Staging App 1",
  "provider": "microsoft",
  "scope": [
    "Mail.Read",
    "User.Read",
    "offline_access"
  ]
}   

Comparative analysis:

Authentication methodDescription
Basic authenticationIt’s easy to setup but less secure, suitable for internal or low-security APIs.
Token-based authenticationOffers a good balance of security and flexibility.
Multi-factor authenticationProvides robust security features and is ideal for third-party access in consumer applications
API KeysEasy to implement but should be used in less critical scenarios.

Real-world example: A common use of OAuth is in social media integrations. For instance, when a user logs into a third-party app using their Google account, the app uses OAuth to authenticate and authorize access to Google services such as Google Calendar events without getting the user’s password.