# Clearbit Company API Replacement

This guide provides step-by-step instructions for migrating from Clearbit's Company API to Tomba's `/companies/find` endpoint.

---

## API Comparison

| Feature               | Clearbit Company API                     | Tomba Company API                |
| --------------------- | ---------------------------------------- | -------------------------------- |
| **Endpoint**          | `company.clearbit.com/v2/companies/find` | `api.tomba.io/v1/companies/find` |
| **Input**             | Domain                                   | Domain                           |
| **Authentication**    | Bearer token                             | API Key + Secret headers         |
| **Rate Limit**        | 600 req/min                              | 300 req/min                      |
| **Company Data**      | ✅                                       | ✅ Enhanced                      |
| **Social Profiles**   | ✅                                       | ✅                               |
| **Logo & Assets**     | ✅                                       | ✅                               |
| **Technology Stack**  | ❌                                       | ✅ 6000+ technologies            |
| **Similar Companies** | ❌                                       | ✅                               |
| **Phone Number**      | Limited                                  | ✅ Verified                      |
| **Email Count**       | ❌                                       | ✅                               |
| **Free Trial**        | 50 calls                                 | 50 searches + 500 verifications  |

---

## Endpoint Migration

### Clearbit Company API

```http
GET https://company.clearbit.com/v2/companies/find?domain=tomba.io
Authorization: Bearer sk_clearbit_xxx
```

### Tomba Company API

```http
GET https://api.tomba.io/v1/companies/find?domain=tomba.io
X-Tomba-Key: your-api-key
X-Tomba-Secret: your-secret-key
```

---

## Response Format Comparison

### Clearbit Response

```json
{
    "id": "027b0d40-016c-40ea-8925-a076fa640992",
    "name": "Tomba",
    "legalName": "Tomba Technology Web Service LLC",
    "domain": "tomba.io",
    "domainAliases": [],
    "url": "https://tomba.io",
    "site": {
        "title": "Tomba - Email Finder",
        "h1": "Find Anyone's Email Address",
        "metaDescription": "Tomba helps you find email addresses",
        "phoneNumbers": ["+1-234-567-8900"]
    },
    "tags": ["Technology", "B2B", "SaaS"],
    "description": "Email finding and verification platform",
    "foundedYear": 2018,
    "location": "123 Tech Street, San Francisco, CA 94105, USA",
    "timeZone": "America/Los_Angeles",
    "utcOffset": -8,
    "geo": {
        "streetNumber": "123",
        "streetName": "Tech Street",
        "subPremise": null,
        "city": "San Francisco",
        "postalCode": "94105",
        "state": "California",
        "stateCode": "CA",
        "country": "United States",
        "countryCode": "US",
        "lat": 37.7749,
        "lng": -122.4194
    },
    "logo": "https://logo.clearbit.com/tomba.io",
    "facebook": {
        "handle": "tombaio"
    },
    "linkedin": {
        "handle": "company/tomba"
    },
    "twitter": {
        "handle": "tomba_io",
        "id": "123456789",
        "followers": 5000
    },
    "crunchbase": {
        "handle": "organization/tomba"
    },
    "emailProvider": false,
    "type": "private",
    "ticker": null,
    "phone": "+1-234-567-8900",
    "metrics": {
        "alexaUsRank": 50000,
        "alexaGlobalRank": 150000,
        "googleRank": 5,
        "employees": 50,
        "employeesRange": "11-50",
        "marketCap": null,
        "raised": 2000000,
        "annualRevenue": null,
        "estimatedAnnualRevenue": "$5M-$10M"
    },
    "category": {
        "sector": "Information Technology",
        "industryGroup": "Software",
        "industry": "Application Software",
        "subIndustry": "Business Intelligence Software",
        "gicsCode": "45103010"
    },
    "tech": ["google_analytics", "stripe"],
    "parent": {
        "domain": null
    }
}
```

### Tomba Response

```json
{
    "data": {
        "organization": "Tomba",
        "email_count": 15,
        "phone_number": "+1-234-567-8900",
        "website": "https://tomba.io",
        "country": "US",
        "state": "California",
        "city": "San Francisco",
        "postal_code": "94105",
        "street": "123 Tech Street",
        "revenue": "5000000-10000000",
        "employees": "11-50",
        "founded": 2018,
        "industry": "Computer Software",
        "description": "Tomba helps you find and verify professional email addresses",
        "logo": "https://d12h6n0d1mbsct.cloudfront.net/logos/tomba-io.jpg",
        "twitter": "tomba_io",
        "linkedin": "tomba",
        "facebook": "tombaio",
        "technologies": [
            {
                "name": "Google Analytics",
                "category": "Analytics",
                "icon": "https://d12h6n0d1mbsct.cloudfront.net/technologies/google-analytics.png"
            },
            {
                "name": "Stripe",
                "category": "Payment",
                "icon": "https://d12h6n0d1mbsct.cloudfront.net/technologies/stripe.png"
            }
        ],
        "similar_domains": ["xxx.io", "xxx.io", "xxx.com"]
    }
}
```

---

## Field Mapping

| Clearbit Field                        | Tomba Field       | Notes                           |
| ------------------------------------- | ----------------- | ------------------------------- |
| `name`                                | `organization`    | Company name                    |
| `domain`                              | N/A               | Input parameter                 |
| `url`                                 | `website`         | Company website                 |
| `description`                         | `description`     | Company description             |
| `foundedYear`                         | `founded`         | Year founded                    |
| `geo.city`                            | `city`            | City location                   |
| `geo.state`                           | `state`           | State/Province                  |
| `geo.country`                         | `country`         | Country code                    |
| `geo.postalCode`                      | `postal_code`     | Postal code                     |
| `geo.streetName` + `geo.streetNumber` | `street`          | Street address                  |
| `logo`                                | `logo`            | Logo URL                        |
| `phone`                               | `phone_number`    | Company phone                   |
| `metrics.employees`                   | `employees`       | Employee count                  |
| `metrics.estimatedAnnualRevenue`      | `revenue`         | Revenue estimate                |
| `facebook.handle`                     | `facebook`        | Facebook username               |
| `linkedin.handle`                     | `linkedin`        | LinkedIn handle                 |
| `twitter.handle`                      | `twitter`         | Twitter handle                  |
| `tech`                                | `technologies`    | **Enhanced array with details** |
| N/A                                   | `email_count`     | **New: Total emails available** |
| N/A                                   | `similar_domains` | **New: Competitor list**        |

---

## Code Examples

### Node.js / JavaScript

**Before (Clearbit):**

```javascript
const clearbit = require("clearbit")("sk_clearbit_xxx");

async function getCompany(domain) {
    try {
        const company = await clearbit.Company.find({ domain });
        return {
            name: company.name,
            employees: company.metrics?.employees,
            industry: company.category?.industry,
            location: `${company.geo?.city}, ${company.geo?.country}`,
        };
    } catch (error) {
        console.error("Clearbit error:", error);
        throw error;
    }
}
```

**After (Tomba):**

```javascript
const axios = require("axios");

async function getCompany(domain) {
    try {
        const response = await axios.get(
            "https://api.tomba.io/v1/companies/find",
            {
                params: { domain },
                headers: {
                    "X-Tomba-Key": process.env.TOMBA_API_KEY,
                    "X-Tomba-Secret": process.env.TOMBA_API_SECRET,
                },
            },
        );

        const company = response.data.data;
        return {
            name: company.organization,
            employees: company.employees,
            industry: company.industry,
            location: `${company.city}, ${company.country}`,
            // Bonus fields not in Clearbit
            emailCount: company.email_count,
            technologies: company.technologies?.map((t) => t.name),
            competitors: company.similar_domains,
        };
    } catch (error) {
        console.error("Tomba error:", error);
        throw error;
    }
}

// Usage
getCompany("stripe.com").then(console.log);
```

### Python

**Before (Clearbit):**

```python
import clearbit

clearbit.key = 'sk_clearbit_xxx'

def get_company(domain):
    try:
        company = clearbit.Company.find(domain=domain)
        return {
            'name': company['name'],
            'employees': company.get('metrics', {}).get('employees'),
            'industry': company.get('category', {}).get('industry'),
            'location': f"{company.get('geo', {}).get('city')}, {company.get('geo', {}).get('country')}"
        }
    except clearbit.errors.NotFoundError:
        return None
```

**After (Tomba):**

```python
import requests
import os

def get_company(domain):
    try:
        response = requests.get(
            'https://api.tomba.io/v1/companies/find',
            params={'domain': domain},
            headers={
                'X-Tomba-Key': os.getenv('TOMBA_API_KEY'),
                'X-Tomba-Secret': os.getenv('TOMBA_API_SECRET')
            }
        )
        response.raise_for_status()

        company = response.json()['data']
        return {
            'name': company['organization'],
            'employees': company.get('employees'),
            'industry': company.get('industry'),
            'location': f"{company.get('city')}, {company.get('country')}",
            # Bonus fields
            'email_count': company.get('email_count'),
            'technologies': [t['name'] for t in company.get('technologies', [])],
            'competitors': company.get('similar_domains', [])
        }
    except requests.exceptions.HTTPError as e:
        if e.response.status_code == 404:
            return None
        raise

# Usage
company = get_company('stripe.com')
print(company)
```

### PHP

**Before (Clearbit):**

```php
<?php
require 'vendor/autoload.php';

use Clearbit\Clearbit;

Clearbit::setApiKey('sk_clearbit_xxx');

function getCompany($domain) {
    try {
        $company = Clearbit::company()->find(['domain' => $domain]);

        return [
            'name' => $company->name,
            'employees' => $company->metrics->employees ?? null,
            'industry' => $company->category->industry ?? null,
            'location' => "{$company->geo->city}, {$company->geo->country}"
        ];
    } catch (\Clearbit\Errors\NotFoundError $e) {
        return null;
    }
}
```

**After (Tomba):**

```php
<?php
require 'vendor/autoload.php';

use GuzzleHttp\Client;

function getCompany($domain) {
    $client = new Client();

    try {
        $response = $client->get('https://api.tomba.io/v1/companies/find', [
            'query' => ['domain' => $domain],
            'headers' => [
                'X-Tomba-Key' => getenv('TOMBA_API_KEY'),
                'X-Tomba-Secret' => getenv('TOMBA_API_SECRET')
            ]
        ]);

        $company = json_decode($response->getBody())->data;

        return [
            'name' => $company->organization,
            'employees' => $company->employees ?? null,
            'industry' => $company->industry ?? null,
            'location' => "{$company->city}, {$company->country}",
            // Bonus fields
            'email_count' => $company->email_count ?? 0,
            'technologies' => array_map(fn($t) => $t->name, $company->technologies ?? []),
            'competitors' => $company->similar_domains ?? []
        ];
    } catch (\GuzzleHttp\Exception\ClientException $e) {
        if ($e->getResponse()->getStatusCode() === 404) {
            return null;
        }
        throw $e;
    }
}

// Usage
$company = getCompany('stripe.com');
print_r($company);
```

### Ruby

**Before (Clearbit):**

```ruby
require 'clearbit'

Clearbit.key = 'sk_clearbit_xxx'

def get_company(domain)
  company = Clearbit::Enrichment::Company.find(domain: domain)

  {
    name: company.name,
    employees: company.metrics&.employees,
    industry: company.category&.industry,
    location: "#{company.geo&.city}, #{company.geo&.country}"
  }
rescue Clearbit::NotFoundError
  nil
end
```

**After (Tomba):**

```ruby
require 'httparty'

def get_company(domain)
  response = HTTParty.get(
    'https://api.tomba.io/v1/companies/find',
    query: { domain: domain },
    headers: {
      'X-Tomba-Key' => ENV['TOMBA_API_KEY'],
      'X-Tomba-Secret' => ENV['TOMBA_API_SECRET']
    }
  )

  return nil if response.code == 404
  raise "API Error: #{response.code}" unless response.success?

  company = response.parsed_response['data']

  {
    name: company['organization'],
    employees: company['employees'],
    industry: company['industry'],
    location: "#{company['city']}, #{company['country']}",
    # Bonus fields
    email_count: company['email_count'],
    technologies: company['technologies']&.map { |t| t['name'] },
    competitors: company['similar_domains']
  }
end

# Usage
company = get_company('stripe.com')
puts company
```

---

## Enhanced Features

### Technology Stack Detection

Tomba provides detailed technology information not available in Clearbit:

```javascript
const response = await axios.get("https://api.tomba.io/v1/companies/find", {
    params: { domain: "shopify.com" },
    headers: {
        "X-Tomba-Key": process.env.TOMBA_API_KEY,
        "X-Tomba-Secret": process.env.TOMBA_API_SECRET,
    },
});

console.log("Technologies used:");
response.data.data.technologies.forEach((tech) => {
    console.log(`- ${tech.name} (${tech.category})`);
});

// Output:
// - Google Analytics (Analytics)
// - Stripe (Payment Processing)
// - Cloudflare (CDN)
// - Shopify (E-commerce)
// - Mailchimp (Email Marketing)
```

### Similar Companies / Competitors

Find competitors automatically:

```javascript
const company = response.data.data;
console.log(`Companies similar to ${company.organization}:`);
console.log(company.similar_domains);

// Output:
// ['bigcommerce.com', 'woocommerce.com', 'magento.com']
```

### Email Count

Know how many contacts are available:

```javascript
const company = response.data.data;
console.log(
    `${company.email_count} contacts available at ${company.organization}`,
);

// Output: "147 contacts available at Shopify"
```

---

## Error Handling

### Clearbit Errors

```javascript
try {
    const company = await clearbit.Company.find({ domain });
} catch (error) {
    if (error.type === "not_found") {
        // Company not found
    } else if (error.type === "rate_limit") {
        // Rate limited
    } else if (error.type === "invalid_request") {
        // Bad request
    }
}
```

### Tomba Errors

```javascript
try {
    const response = await axios.get("https://api.tomba.io/v1/companies/find", {
        params: { domain },
        headers: {
            "X-Tomba-Key": process.env.TOMBA_API_KEY,
            "X-Tomba-Secret": process.env.TOMBA_API_SECRET,
        },
    });
} catch (error) {
    if (error.response?.status === 404) {
        // Company not found
        console.log("Company not found in database");
    } else if (error.response?.status === 429) {
        // Rate limited
        console.log("Rate limit exceeded");
    } else if (error.response?.status === 400) {
        // Bad request
        console.log("Invalid domain format");
    } else if (error.response?.status === 401) {
        // Authentication failed
        console.log("Invalid API credentials");
    }
}
```

---

## Testing

### Sample Test Cases

```javascript
const assert = require("assert");

describe("Company API Migration", () => {
    it("should return company data for valid domain", async () => {
        const company = await getCompany("stripe.com");

        assert(company.name);
        assert(company.location);
        assert(company.industry);
        assert.ok(company.emailCount > 0); // New field
    });

    it("should return null for non-existent domain", async () => {
        const company = await getCompany("thisdoesnotexist12345.com");
        assert.strictEqual(company, null);
    });

    it("should include technology data", async () => {
        const company = await getCompany("shopify.com");
        assert(Array.isArray(company.technologies));
        assert(company.technologies.length > 0);
    });

    it("should include similar companies", async () => {
        const company = await getCompany("salesforce.com");
        assert(Array.isArray(company.competitors));
    });
});
```

---

## Migration Checklist

- [ ] Update authentication to use API Key + Secret headers
- [ ] Change base URL to `api.tomba.io/v1`
- [ ] Update field mappings in your code
- [ ] Add handling for new fields (technologies, similar_domains, email_count)
- [ ] Update error handling for Tomba response codes
- [ ] Test with sample domains
- [ ] Update type definitions/interfaces
- [ ] Test edge cases (invalid domains, rate limits)
- [ ] Deploy to staging environment
- [ ] Monitor API responses
- [ ] Deploy to production

---

## Next Steps

- [Person API Migration](/migration/clearbit/person-api) - Enrich person data
- [Combined API Migration](/migration/clearbit/combined-api) - Get person + company data
- [Full API Documentation](https://docs.tomba.io)

---

**Need help with migration?**

Contact our support team at [support@tomba.io](mailto:support@tomba.io) for personalized migration assistance.
