B2B Data Enrichment API Integration Guide
Build a reliable B2B data enrichment pipeline on the LeadMagic API, with code examples, rate-limit handling, caching, and async patterns.
To integrate a B2B enrichment API, send authenticated POST requests from your backend (LeadMagic uses an X-API-Key header at https://api.leadmagic.io), back off on HTTP 429 using the rate-limit headers, cache results so you don't pay twice for the same lookup, and move bulk work onto a queue. The rest of this guide shows each pattern in code.
Most teams start with a simple question: how do we add professional context to these leads? If you have a business contact's email, Email to Profile can find a B2B profile URL; Profile Search is a separate lookup for available professional details.
It's easy to treat enrichment as a simple fetch request and call it a day. If you're building for scale, you need to think about rate limits, data accuracy, caching, and error handling. A poorly implemented integration will either burn through your budget or crash your application when you hit a spike in traffic. This guide covers the technical patterns you need to build a professional-grade enrichment engine.
Getting Started with the LeadMagic API
The LeadMagic API is a set of JSON POST endpoints. The Email Finder costs 1 credit per valid email found, with no charge when nothing is found. Before you write any code, you'll need an API key from your dashboard.
Here's the basic structure of a request to find a work email. Profile enrichment is a separate endpoint.
async function findLeadEmail(firstName, lastName, domain) {
const apiKey = process.env.LEADMAGIC_API_KEY;
const url = "https://api.leadmagic.io/v1/people/email-finder";
try {
const response = await fetch(url, {
method: "POST",
headers: {
"X-API-Key": apiKey,
"Content-Type": "application/json",
},
body: JSON.stringify({
first_name: firstName,
last_name: lastName,
domain: domain,
}),
signal: AbortSignal.timeout(30_000),
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(`API Error: ${response.status} - ${errorData.detail ?? errorData.message}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error("Enrichment failed:", error.message);
throw error;
}
}This snippet shows the fundamental pattern. We use the X-API-Key header for authentication and send a JSON body with the lead's details. Notice the error handling. Always check response.ok before trusting the body; errors follow the RFC 9457 problem-details format. The same endpoint also accepts company_name instead of domain, or a profile_url.
Real-Time vs. Batch Enrichment
One of the first architectural decisions you'll make is whether to enrich data in real-time or in batches.
Real-Time Enrichment
This is best for user-facing applications. For example, if a user enters a domain into your search bar, you want to show them company details immediately. Real-time enrichment provides the best user experience but puts more pressure on your API limits and requires low-latency responses.
Batch Enrichment
If you're processing a CSV of 10,000 leads, you don't want to fire 10,000 concurrent requests; you'll hit rate limits immediately. Use a queue, process leads in chunks, and pace them off the RateLimit-Remaining and RateLimit-Reset headers on each response. For large jobs, LeadMagic's bulk API (POST /bulk/submit) runs the rows asynchronously for you. This is much more stable for background jobs and CRM syncing.
Handling Rate Limits and Errors
Every API has limits. If you ignore them, you'll get 429 "Too Many Requests" errors. LeadMagic returns IETF-style rate-limit headers and a Retry-After header on 429s. A reliable integration reads them and backs off exponentially.
Exponential backoff means that if a request fails due to rate limiting, you wait a short time before retrying. If it fails again, you wait longer. This prevents you from hammering the server and gives the API time to reset your quota.
async function fetchWithRetry(url, options, retries = 3, backoff = 1000) {
const response = await fetch(url, options);
if (response.status === 429 && retries > 0) {
const retryAfter = Number(response.headers.get("Retry-After"));
const waitMs = Number.isFinite(retryAfter) && retryAfter > 0
? Math.max(backoff, retryAfter * 1000)
: backoff;
await new Promise((resolve) => setTimeout(resolve, waitMs));
return fetchWithRetry(url, options, retries - 1, backoff * 2);
}
return response;
}This example retries only a rejected 429, which consumes no credits. It uses Retry-After when it contains seconds and doubles the fallback wait (backoff * 2). Add random jitter so parallel workers don't retry in lockstep. Set a timeout on each request; if a timeout, connection failure, or 5xx leaves the outcome uncertain, reconcile it before retrying a billable lookup.
Data Normalization and Caching
Data from different sources often comes in different formats. One API might return "United States," while another returns "US." Before you save data to your database, you should normalize it. This makes your data much easier to query later.
Caching matters too. Enrichment credits cost money. If you've already enriched alex.rivera@example.com today, you shouldn't pay to enrich it again five minutes later.
We recommend a two-tier caching strategy:
- Short-term cache (Redis): Store results for 24-48 hours. This handles duplicate requests in the same session or batch.
- Long-term storage (Postgres/MongoDB): Store the enriched profile in your main database. Set a "last_enriched_at" timestamp. Only re-enrich if the data is older than 30 or 90 days.
How much a cache saves depends on how much your inputs overlap; measure your duplicate-request rate for a week before sizing it.
Advanced Patterns: Webhooks and Async Processing
For heavy workloads, you shouldn't wait for the API response in your main thread. Instead, use an asynchronous pattern.
- Your application receives a request to enrich a lead.
- You add the lead's ID to a message queue (like RabbitMQ or AWS SQS).
- A worker process picks up the message and calls the LeadMagic API.
- The worker updates your database with the results.
This keeps your main application fast and responsive. If the enrichment API is slow or down, your users won't even notice because the work is happening in the background.
Security Best Practices
Your API key is a direct line to your credits. If it leaks, someone else can use your budget.
- Never store keys in your code. Use environment variables.
- Never call the API from the frontend. A user can easily open the network tab and steal your key. Always proxy your requests through a backend server.
- Rotate your keys regularly. If you suspect a leak, revoke the old key and generate a new one immediately.
Integrating Company Enrichment
Understanding the company matters as much as the person. Company enrichment returns available details such as industry and headcount. For new integrations, use the Company Search API reference; funding and technographics are available as separate enrichments.
The integration pattern is identical to the people finder: send a POST with the identifier and get back structured JSON. Combining these two endpoints allows you to build a complete picture of your prospects.
Key Takeaways
- Use the
X-API-Keyheader and POST requests for the LeadMagic API. - Implement exponential backoff to handle 429 rate limit errors.
- Cache results to save on pricing and improve performance.
- Normalize data before saving it to your database.
- Always proxy API calls through your backend to keep your keys secure.
- Pay for results, not attempts: the Email Finder charges only for valid emails found.
Bottom Line
Integrating an enrichment API isn't just about making a network call. It's about building a reliable system that handles errors, saves money, and provides accurate data to your team. By following these patterns, you'll create a data pipeline that scales with your business.
Ready to build? Read the full API documentation and start enriching your leads.
Need help with your integration? Our engineering team is always happy to chat about best practices and custom workflows.
Sources and review
Topic path
Go deeper on Enrichment for Developers
API-first enrichment for GTM engineers, data enrichment, scraping, CLI, MCP, and automation.
Keep reading
Build an email validation waterfall in Clay: provider ordering, conditional catch-all resolution, and credit math that holds up.
Integrate email verification with curl, Python, and Node.js. Covers responses, catch-all handling, batching, and production error strategies.
Compare Clearbit and other tools for hubspot enrichment. See the documented features and check which inputs, outputs and billing terms fit your team.