# How to Use Maigret as a Python Library in Your Own Projects

> Integrate Maigret into your Python projects. Programmatically search usernames asynchronously using the Maigret Python library for advanced automation and custom tools.

- Repository: [Soxoj/maigret](https://github.com/soxoj/maigret)
- Tags: how-to-guide
- Published: 2026-04-30

---

**Yes, Maigret can be imported as a standard Python module, allowing you to programmatically execute username searches via its asynchronous `search` function without invoking the command-line interface.**

The soxoj/maigret repository bundles a fully-featured Python API alongside its CLI. When you install the package, you gain access to internal modules that handle site database parsing, configuration management, and asynchronous HTTP checking, enabling seamless integration into custom OSINT pipelines, web services, or automation scripts.

## Public API Entry Points

The library exposes its public interface through [`maigret/__init__.py`](https://github.com/soxoj/maigret/blob/main/maigret/__init__.py), which re-exports two primary callables for external use.

### The `search` Function

Defined in [`maigret/checking.py`](https://github.com/soxoj/maigret/blob/main/maigret/checking.py), `search` is the asynchronous core that performs username lookups across Maigret's site database. It accepts a username, a dictionary of sites, a logger instance, and optional parameters such as timeout and proxy settings. Because it is a coroutine, it must be awaited inside an async context.

### The `cli` Wrapper

Also exported from [`maigret/__init__.py`](https://github.com/soxoj/maigret/blob/main/maigret/__init__.py), `cli` provides a thin wrapper around the `maigret.main.maigret.run` function located in [`maigret/maigret.py`](https://github.com/soxoj/maigret/blob/main/maigret/maigret.py). This is the same entry point used by the command-line tool, useful if you need to trigger a full CLI run programmatically.

## Core Library Workflow

To embed Maigret functionality in your project, follow three distinct steps: load the configuration, initialize the site database, and execute the search.

### Loading Settings from [`maigret/maigret/settings.py`](https://github.com/soxoj/maigret/blob/main/maigret/maigret/settings.py)

The `Settings` class manages configuration paths and default values. Call `load()` to initialize the settings object and retrieve the path to the bundled JSON site database.

```python
from maigret.maigret.settings import Settings

settings = Settings()
loaded, err = settings.load()
if not loaded:
    raise RuntimeError(f"Failed to load settings: {err}")

```

### Initializing the Site Database with [`maigret/maigret/sites.py`](https://github.com/soxoj/maigret/blob/main/maigret/maigret/sites.py)

The `MaigretDatabase` class parses the JSON file containing site metadata. Use `load_from_path()` with `settings.sites_db_path` to populate a dictionary of `MaigretSite` objects.

```python
from maigret.maigret.sites import MaigretDatabase

db = MaigretDatabase().load_from_path(settings.sites_db_path)
site_dict = db.sites  # Dictionary of site objects keyed by site name

```

### Executing the Async Search

Import `search` from the top-level package, then await it with the username and site dictionary. Pass a configured `logging.Logger` for debug output.

```python
import logging
from maigret import search

async def run_check(username: str):
    logger = logging.getLogger("maigret_lib")
    logger.setLevel(logging.INFO)
    
    results = await search(
        username=username,
        site_dict=site_dict,
        logger=logger,
        timeout=5
    )
    return results

```

## Complete Implementation Example

The following runnable script demonstrates the full integration pattern, including async setup and result processing:

```python

# example.py

import asyncio
import logging

# Public API

from maigret import search               # <-- alias for `maigret.checking.maigret`

from maigret.maigret.settings import Settings
from maigret.maigret.sites import MaigretDatabase

# --------------------------------------------------------------------

# 1. Load configuration

# --------------------------------------------------------------------

settings = Settings()
loaded, err = settings.load()
if not loaded:
    raise RuntimeError(f"Failed to load settings: {err}")

# --------------------------------------------------------------------

# 2. Load the site database (JSON file shipped with the package)

# --------------------------------------------------------------------

db = MaigretDatabase().load_from_path(settings.sites_db_path)

# --------------------------------------------------------------------

# 3. Define a tiny async wrapper that calls the library

# --------------------------------------------------------------------

async def run_search(username: str):
    logger = logging.getLogger("my_app")
    logger.setLevel(logging.INFO)

    # `search` returns a dict keyed by site name → result objects

    results = await search(
        username=username,
        site_dict=db.sites,        # the dict of MaigretSite objects

        logger=logger,
        timeout=5,                 # seconds per request

        # proxy="socks5://127.0.0.1:1080",

        # is_parsing_enabled=True,

    )
    return results

# --------------------------------------------------------------------

# 4. Run the async function (you can also embed this in a larger async app)

# --------------------------------------------------------------------

if __name__ == "__main__":
    username_to_check = "alice"
    all_results = asyncio.run(run_search(username_to_check))

    # Simple pretty-print of the outcome

    for site, data in all_results.items():
        status = data["status"]
        print(f"{site:30} → {status.status.name}")

```

## Integration Patterns

### Async Web Applications

If your project already uses an async framework like FastAPI or Quart, simply `await search(...)` directly within your route handlers. Ensure you reuse the database and settings objects across requests to avoid reloading the JSON file on every call.

### Sync Scripts

For synchronous codebases, wrap the async call using `asyncio.run()` as shown in the example above, or use `asyncio.get_event_loop().run_until_complete()` if managing an existing loop.

## Summary

- **Import the public API** via `from maigret import search` to access the async search functionality defined in [`maigret/checking.py`](https://github.com/soxoj/maigret/blob/main/maigret/checking.py).
- **Configure settings** using [`maigret/maigret/settings.py`](https://github.com/soxoj/maigret/blob/main/maigret/maigret/settings.py) to load paths and defaults.
- **Initialize the database** with `MaigretDatabase` from [`maigret/maigret/sites.py`](https://github.com/soxoj/maigret/blob/main/maigret/maigret/sites.py) to parse the bundled site definitions.
- **Await the search** coroutine with a valid site dictionary, logger, and optional network parameters.
- **Handle results** as a dictionary mapping site names to result objects containing status and metadata.

## Frequently Asked Questions

### Can I use Maigret as a Python library without installing the CLI?

Yes. Installing the `maigret` package via pip installs both the CLI and the library modules. You can import `search`, `Settings`, and `MaigretDatabase` in your own code without ever invoking the command-line tool, giving you programmatic control over execution.

### What does the `search` function return?

The `search` function returns a dictionary where each key is a site name (string) and each value is a result object. According to the implementation in [`maigret/checking.py`](https://github.com/soxoj/maigret/blob/main/maigret/checking.py), these objects contain a `"status"` key with a status enum indicating whether the username was found, not found, or if an error occurred during the check.

### How do I configure proxies when using Maigret as a library?

Pass the optional `proxy` parameter directly to the `search` function. Accept the same string format used by the CLI (e.g., `"socks5://127.0.0.1:1080"` or `"http://proxy.example.com:8080"`). This overrides any proxy settings loaded from the configuration files.

### Is it possible to use a custom site database JSON file?

Yes. Instead of loading from `settings.sites_db_path`, instantiate `MaigretDatabase()` and call `load_from_path()` with the absolute path to your custom JSON file. This allows you to maintain a curated list of sites or test against a modified database without altering the package defaults.