Integrating third-party APIs can often turn into a tedious routine: copy-pasting the same cURL boilerplate, manually decoding JSON responses, and reinventing rate-limit and error-handling logic for every new project. If you are working with cryptocurrency data and leveraging the Nansen AI API, a new library by Igor Sazonov (tigusigalpa) called nansen-php promises to eliminate this headache.
In this article, we will take a comprehensive look at the tigusigalpa/nansen-php repository 1. We will explore its architecture, highlight its key features, and understand why it deserves the attention of PHP developers—especially those working within the Laravel ecosystem.
What is nansen-php?
nansen-php is a framework-agnostic PHP 8.1+ client designed specifically for the Nansen AI API. It provides developers with an elegant, fluent (chainable) interface for making requests, returns strongly typed Data Transfer Objects (DTOs), automatically handles rate limits with built-in retry logic, and offers first-class support for the Laravel framework (versions 10 through 13).
The primary goal of the library is to hide all the HTTP request boilerplate behind an expressive API, making your code read almost like a natural language sentence.
Key Features and Architectural Decisions
After reviewing the library's source code, several strong architectural choices stand out, making it an excellent tool for Nansen AI integration.
1. Expressive Fluent API
Instead of manually constructing arrays of parameters and passing them to an HTTP client, nansen-php employs the Builder pattern. The RequestBuilder class allows you to construct a query step-by-step:
use Tigusigalpa\Nansen\NansenClient;
$client = NansenClient::create(['api_key' => 'YOUR_API_KEY']);
$netflows = $client
->smartMoney()
->netflows()
->chains(['ethereum'])
->limit(10)
->get();
Every modifier method (chains(), filters(), orderBy(), limit(), offset(), page()) clones the current builder instance and returns a new one. This ensures immutability, allowing you to reuse base queries without unintended side effects.
2. Strict Typing and Data Transfer Objects (DTOs)
One of the biggest pain points when working with external APIs in PHP is dealing with loosely structured, associative arrays. nansen-php solves this by returning typed objects.
All responses inherit from a base Dto class. This means that lists are returned as real collections that you can iterate over, and property access is done via object properties rather than array keys.
An interesting and highly practical architectural decision is that every DTO retains the original, untouched API response in a ->raw property. If Nansen adds a new field to their API response tomorrow, and the library hasn't been updated yet, you can still access that data immediately:
// Accessing new, undocumented fields future-proofs your application
$brandNewField = $netflows->raw['data'][0]['brand_new_field'] ?? null;
This guarantees that you will never lose data due to a lagging library version.
3. Automatic Rate Limit Handling and Retry Logic
Working with robust APIs often involves encountering 429 Too Many Requests errors. The Client class within the Http namespace takes full responsibility for handling these scenarios.
When a 429 status is received, the client automatically extracts the Retry-After, X-RateLimit-Remaining, or RateLimit-Remaining headers. It then pauses script execution for the required duration using usleep() before automatically retrying the request.
For server-side errors (HTTP statuses >= 500), the library implements an exponential backoff algorithm. The number of retry attempts and the base delay are easily configurable.
4. Clear Exception Hierarchy
The library does not simply throw generic exceptions. It provides a structured hierarchy extending from a base ApiException:
RateLimitException: Thrown when the rate limit is exceeded and all retry attempts have been exhausted. It provides usefulretryAfter()andremaining()methods.UnauthorizedException: Thrown for 401 statuses, typically indicating an invalid or expired API key.NotFoundException: Thrown for 404 statuses when a resource or address cannot be found.
This hierarchy allows developers to easily catch specific errors and handle them gracefully within their applications.
5. HTTP Client Agnosticism (PSR-18)
By default, nansen-php utilizes Guzzle (guzzlehttp/guzzle ). However, the library is fully compliant with the PSR-18 standard. You can inject any other PSR-18 compatible HTTP client by passing it to the constructor or binding it via the Laravel service container. This is particularly useful if you need to use a client with custom middleware, logging, or specific SSL configurations.
6. First-Class Laravel Integration
While the library is framework-agnostic at its core, it provides a seamless developer experience for Laravel users. The package includes an auto-discovered NansenServiceProvider that automatically configures the NansenClient using settings published to config/nansen.php.
It also provides a Nansen facade, enabling you to write highly concise code:
use Tigusigalpa\Nansen\Laravel\Facades\Nansen;
$balances = Nansen::profiler()
->addressBalance('0x1234...')
->get();
Supported Endpoints
As of version 1.0.0, the library covers the core and most highly requested Nansen AI endpoints:
| Category | Available Endpoints |
|---|---|
| Smart Money |
netflows(), holdings(), dexTrades()
|
| Token God Mode |
tokenScreener(), flowIntelligence(), whoBoughtSold()
|
| Profiler |
addressBalance(), addressDexTrades(), addressLabels()
|
| Portfolio | defiHoldings() |
| Search |
general(), entity()
|
| Historical Data | Access to v1beta1 backtesting endpoints |
Because every endpoint shares the same set of modifiers, once you learn how to query one endpoint, you immediately know how to query them all.
Code Quality and Testing
An analysis of the repository reveals a high standard of engineering culture:
PHP 8.1+ Features: The codebase actively utilizes modern PHP features such as
readonlyproperties,matchexpressions, and strict typing.Testing: The presence of a
testsdirectory and aphpunit.xmlconfiguration file indicates that the code is covered by tests. According to the README, the test suite runs against a mocked HTTP client, meaning no real API key or network access is required to run them.Standards: The use of
declare(strict_types=1);is consistent across all files.
Conclusion
The tigusigalpa/nansen-php repository is an exemplary model of what a modern PHP API SDK should look like. The author didn't just wrap cURL requests in classes; they created a thoughtful architecture that solves real developer pain points: response typing, rate limit handling, and code readability.
Whether you are building a complex crypto analytics platform on Laravel or a small, standalone PHP script to monitor wallets, this library will save you hours of boilerplate coding and make your codebase cleaner and more reliable.
The repository is MIT licensed and open for contributions. If you are working with the Nansen API, it is definitely worth requiring tigusigalpa/nansen-php in your composer.json.
Top comments (0)