# SDK snippets

There is no package to install: the API is small enough that a dozen lines cover it. Copy the client for your language, or generate one from the [OpenAPI spec](/v1/openapi.json) with any OpenAPI generator.

Each snippet reads the key from `MAILSFIT_KEY`, verifies one address, verifies a batch and reads the balance.

```javascript
// mailsfit.mjs (Node 18+, Deno, Bun, browsers server-side only)
const API = "https://api.mails.fit/v1";

export function mailsfit(key = process.env.MAILSFIT_KEY) {
  async function call(method, path, body) {
    const res = await fetch(API + path, {
      method,
      headers: { Authorization: `Bearer ${key}`, "Content-Type": "application/json" },
      body: body && JSON.stringify(body),
    });
    const data = await res.json();
    if (!res.ok && res.status !== 202) throw new Error(`${res.status} ${data.error?.code ?? data.error}`);
    return data;
  }
  return {
    verify: (email, wait = 25) => call("POST", "/verify", { email, wait }),
    verifyBatch: (emails, wait = 25) => call("POST", "/verify/batch", { emails, wait }),
    result: (id) => call("GET", `/verify/${id}`),
    credits: () => call("GET", "/credits"),
  };
}
```

```python
# mailsfit.py (requests)
import os
import requests

class Mailsfit:
    def __init__(self, key=None, base="https://api.mails.fit/v1"):
        self.base = base
        self.s = requests.Session()
        self.s.headers["Authorization"] = f"Bearer {key or os.environ['MAILSFIT_KEY']}"

    def _call(self, method, path, **kw):
        r = self.s.request(method, self.base + path, timeout=60, **kw)
        if r.status_code >= 400:
            raise RuntimeError(f"{r.status_code} {r.text}")
        return r.json()

    def verify(self, email, wait=25):
        return self._call("POST", "/verify", json={"email": email, "wait": wait})

    def verify_batch(self, emails, wait=25):
        return self._call("POST", "/verify/batch", json={"emails": emails, "wait": wait})

    def result(self, id):
        return self._call("GET", f"/verify/{id}")

    def credits(self):
        return self._call("GET", "/credits")["balance"]
```

```go
// Package mailsfit is a minimal client for the mails.fit API.
package mailsfit

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
	"time"
)

type Client struct {
	Key  string
	Base string
	HTTP *http.Client
}

func New() *Client {
	return &Client{Key: os.Getenv("MAILSFIT_KEY"), Base: "https://api.mails.fit/v1", HTTP: &http.Client{Timeout: 60 * time.Second}}
}

func (c *Client) call(method, path string, in, out any) error {
	var body bytes.Buffer
	if in != nil {
		if err := json.NewEncoder(&body).Encode(in); err != nil {
			return err
		}
	}
	req, err := http.NewRequest(method, c.Base+path, &body)
	if err != nil {
		return err
	}
	req.Header.Set("Authorization", "Bearer "+c.Key)
	req.Header.Set("Content-Type", "application/json")
	res, err := c.HTTP.Do(req)
	if err != nil {
		return err
	}
	defer res.Body.Close()
	if res.StatusCode >= 400 {
		return fmt.Errorf("mails.fit: HTTP %d", res.StatusCode)
	}
	return json.NewDecoder(res.Body).Decode(out)
}

func (c *Client) Verify(email string) (map[string]any, error) {
	var v map[string]any
	return v, c.call("POST", "/verify", map[string]any{"email": email}, &v)
}

func (c *Client) VerifyBatch(emails []string) (map[string]any, error) {
	var v map[string]any
	return v, c.call("POST", "/verify/batch", map[string]any{"emails": emails}, &v)
}
```

```php
<?php
// Mailsfit.php (ext-curl, ext-json)
final class Mailsfit
{
    public function __construct(
        private string $key = "",
        private string $base = "https://api.mails.fit/v1",
    ) {
        $this->key = $key ?: (string) getenv("MAILSFIT_KEY");
    }

    private function call(string $method, string $path, ?array $body = null): array
    {
        $ch = curl_init($this->base . $path);
        curl_setopt_array($ch, [
            CURLOPT_CUSTOMREQUEST => $method,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 60,
            CURLOPT_HTTPHEADER => ["Authorization: Bearer {$this->key}", "Content-Type: application/json"],
            CURLOPT_POSTFIELDS => $body === null ? null : json_encode($body),
        ]);
        $raw = curl_exec($ch);
        $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
        if ($raw === false || $status >= 400) {
            throw new RuntimeException("mails.fit: HTTP $status");
        }
        return json_decode($raw, true);
    }

    public function verify(string $email): array { return $this->call("POST", "/verify", ["email" => $email]); }
    public function verifyBatch(array $emails): array { return $this->call("POST", "/verify/batch", ["emails" => $emails]); }
    public function credits(): int { return $this->call("GET", "/credits")["balance"]; }
}
```

```rust
// Cargo.toml: reqwest = { version = "0.12", features = ["json"] }, serde_json = "1"
use serde_json::{json, Value};

pub struct Mailsfit {
    key: String,
    http: reqwest::Client,
}

impl Mailsfit {
    pub fn from_env() -> Result<Self, std::env::VarError> {
        Ok(Self { key: std::env::var("MAILSFIT_KEY")?, http: reqwest::Client::new() })
    }

    async fn call(&self, req: reqwest::RequestBuilder) -> reqwest::Result<Value> {
        req.bearer_auth(&self.key).send().await?.error_for_status()?.json().await
    }

    pub async fn verify(&self, email: &str) -> reqwest::Result<Value> {
        self.call(self.http.post("https://api.mails.fit/v1/verify").json(&json!({ "email": email }))).await
    }

    pub async fn verify_batch(&self, emails: &[&str]) -> reqwest::Result<Value> {
        self.call(self.http.post("https://api.mails.fit/v1/verify/batch").json(&json!({ "emails": emails }))).await
    }

    pub async fn credits(&self) -> reqwest::Result<Value> {
        self.call(self.http.get("https://api.mails.fit/v1/credits")).await
    }
}
```

```bash
# Shell: verify every address in emails.txt, 100 per call
split -l 100 emails.txt chunk_
for f in chunk_*; do
  jq -R . "$f" | jq -s '{emails: ., wait: 25}' |
    curl -sS https://api.mails.fit/v1/verify/batch \
      -H "Authorization: Bearer $MAILSFIT_KEY" -H "Content-Type: application/json" -d @- |
    jq -r '.results[] | [.email, (.status // .error.code)] | @csv'
done
```
