Authentication overview

Lob.com uses API keys as its primary method for authenticating requests to its Address Verification and Print & Mail APIs. This approach provides a direct method for applications to prove their identity and obtain authorization to access services. API keys are unique identifiers that are passed with each request to the Lob.com API, allowing the system to verify the sender's legitimacy and permissions. The use of distinct test and live API keys facilitates development and production environments, ensuring that testing activities do not affect live data or incur production costs. This separation is a common practice in API development for managing different stages of an application's lifecycle, as detailed in the Mozilla Developer Network's API key definition.

During the authentication process, the provided API key is checked against the Lob.com system to confirm its validity and the associated account's access rights. If the key is valid and authorized, the API request is processed. If the key is invalid, missing, or unauthorized, the request is rejected, typically with an HTTP 401 Unauthorized status code. This mechanism helps protect against unauthorized access and ensures the integrity of data processed through Lob.com's services, which include postal address verification and the automated sending of physical mail pieces such as postcards and letters.

Supported authentication methods

Lob.com exclusively supports API key authentication for programmatic access to its services. This method involves generating a unique string of characters from the Lob.com dashboard and including it in the header or payload of API requests. There are two primary types of API keys:

  • Test API Keys: Used for development and testing purposes. Requests made with a test key do not incur charges and operate within a sandbox environment, preventing interaction with live postal services or actual address data. This allows developers to integrate and refine their applications without real-world impact.
  • Live API Keys: Required for production environments. Requests made with a live key interact directly with Lob.com's production systems, leading to actual address verifications, mail piece creation, and associated charges. These keys should be handled with strict security protocols.

Below is a table summarizing the authentication method:

Method When to Use Security Level
API Key (Test) Development, testing, sandbox environments Moderate (no access to live data/services)
API Key (Live) Production, live applications, real-world data processing High (requires careful management and protection)

Getting your credentials

To obtain your API keys for Lob.com, you must create an account and access the developer dashboard. The process generally involves the following steps:

  1. Account Creation: Navigate to the Lob.com homepage and sign up for a new account if you don't already have one.
  2. Dashboard Access: Log in to your Lob.com account. This will typically direct you to your dashboard.
  3. Navigate to API Keys: Within the dashboard, look for a section related to 'API Keys', 'Developers', or 'Settings'. The exact navigation path may vary but is usually intuitive. Refer to the Lob.com official documentation for specific steps to locate the API key generation interface.
  4. Generate Keys: You will find options to generate both 'Test' and 'Live' API keys. It is recommended to generate both so you can differentiate between development and production environments. Upon generation, your API key (a long alphanumeric string) will be displayed.
  5. Secure Storage: Immediately copy and securely store your API keys. Live keys, in particular, should be treated as sensitive credentials and never hardcoded into client-side code, exposed in public repositories, or shared unnecessarily.

Lob.com API keys typically begin with test_ for test keys and live_ for live keys, followed by a unique identifier. This prefix helps in quickly identifying the key's environment.

Authenticated request example

Authenticated requests to the Lob.com API typically involve including your API key in the HTTP Basic Authentication header. The username for Basic Authentication is your Lob.com API key, and the password field should be left blank. This method is widely supported across various programming languages and HTTP client libraries. The Lob.com API reference provides detailed instructions and examples for specific endpoints.

Python example (using requests library):


import requests

API_KEY = "YOUR_LIVE_API_KEY" # Replace with your actual live API key

# Example: Verify an address
url = "https://api.lob.com/v1/addresses/verify"
headers = {
    "Content-Type": "application/json"
}

# Basic authentication: username is the API key, password is empty
auth = (API_KEY, '')

payload = {
    "address": {
        "address_line1": "185 Berry St",
        "address_city": "San Francisco",
        "address_state": "CA",
        "address_zip": "94107"
    }
}

try:
    response = requests.post(url, headers=headers, json=payload, auth=auth)
    response.raise_for_status() # Raises HTTPError for bad responses (4xx or 5xx)
    print("Address verification successful:")
    print(response.json())
except requests.exceptions.HTTPError as err:
    print(f"HTTP error occurred: {err}")
except requests.exceptions.RequestException as err:
    print(f"An error occurred: {err}")

Node.js example (using axios library):


const axios = require('axios');

const API_KEY = 'YOUR_LIVE_API_KEY'; // Replace with your actual live API key

// Example: Verify an address
const url = 'https://api.lob.com/v1/addresses/verify';

const payload = {
  address: {
    address_line1: '185 Berry St',
    address_city: 'San Francisco',
    address_state: 'CA',
    address_zip: '94107',
  },
};

axios.post(url, payload, {
  auth: {
    username: API_KEY,
    password: '', // Password is empty for API key authentication
  },
  headers: {
    'Content-Type': 'application/json',
  },
})
.then(response => {
  console.log('Address verification successful:');
  console.log(response.data);
})
.catch(error => {
  if (error.response) {
    // The request was made and the server responded with a status code
    // that falls out of the range of 2xx
    console.error('Error data:', error.response.data);
    console.error('Error status:', error.response.status);
    console.error('Error headers:', error.response.headers);
  } else if (error.request) {
    // The request was made but no response was received
    console.error('Error request:', error.request);
  } else {
    // Something happened in setting up the request that triggered an Error
    console.error('Error message:', error.message);
  }
  console.error('Error config:', error.config);
});

These examples demonstrate how to include the API key using HTTP Basic Authentication. When deploying to production, ensure that the API key is retrieved from a secure environment variable or a secret management service rather than being hardcoded.

Security best practices

Securing your Lob.com API keys is crucial to prevent unauthorized access, potential data breaches, and unexpected charges. Adhering to robust security practices is essential for any API integration. The Twilio API security best practices guide outlines many general principles applicable to Lob.com's API key usage:

  • Environment Variables: Store API keys as environment variables rather than hardcoding them directly into your application's source code. This keeps keys out of version control and build artifacts.
  • Secret Management Services: For more complex deployments, utilize dedicated secret management services like AWS Secrets Manager, Google Cloud Secret Manager, or Azure Key Vault. These services provide secure storage, rotation, and access control for sensitive credentials.
  • Restrict Access: Limit who has access to your API keys. Only individuals or systems that absolutely require access should have it. Implement role-based access control (RBAC) where possible.
  • Never Expose Client-Side: Never embed your API keys directly into client-side code (e.g., JavaScript in a web browser or mobile application). This would expose your key to anyone inspecting the client-side code, allowing them to impersonate your application. All API calls requiring a live key should originate from your secure backend server.
  • IP Whitelisting (if available): If Lob.com offers IP whitelisting functionality, configure it to allow API requests only from known, trusted IP addresses. This adds an additional layer of security by restricting where requests can originate. Always check the Lob.com documentation for the latest security features.
  • Monitor Usage: Regularly monitor your API usage through the Lob.com dashboard. Unusual spikes in usage or unexpected activity could indicate a compromised key.
  • Key Rotation: Periodically rotate your API keys. If a key is compromised, rotating it minimizes the window of vulnerability. Lob.com's dashboard should provide functionality to generate new keys and revoke old ones.
  • Error Handling: Implement robust error handling in your application to gracefully manage authentication failures. Avoid logging API keys in plain text within your application logs.
  • HTTPS/TLS: Ensure all communication with the Lob.com API uses HTTPS (TLS). This encrypts data in transit, protecting your API key and sensitive data from interception. Major HTTP client libraries and cloud environments enforce this by default.