DEV Community

Cover image for Stop Fighting the CryptoPanic API: Meet cryptopanic-php, the Modern PHP SDK
Igor
Igor

Posted on

Stop Fighting the CryptoPanic API: Meet cryptopanic-php, the Modern PHP SDK

Integrating a news aggregator API into your application often sounds straightforward. You just need to pull a few endpoints, parse some JSON, and display the results. However, when working with financial data platforms like CryptoPanic, the reality quickly becomes complicated. You find yourself writing boilerplate code for authentication, handling evolving response schemas, implementing retry logic for rate limits, and managing pagination state. Every project seems to demand the same tedious plumbing.

The CryptoPanic API is an incredibly powerful resource for developers building crypto trackers, trading bots, and portfolio dashboards. Yet, consuming it cleanly in PHP has historically required developers to reinvent the wheel. This is where cryptopanic-php steps in. It is a modern, framework-neutral PHP SDK designed to make fetching crypto news, managing portfolios, and consuming RSS feeds an elegant experience.

In this article, we will explore why you should stop fighting raw cURL requests and start using cryptopanic-php to build robust crypto applications.

Why Another SDK?

When integrating external services, the goal is to spend time building business logic, not wrestling with HTTP clients. cryptopanic-php was built with modern PHP practices in mind, targeting PHP 8.1 and above. It provides a typed, predictable, and safe interface to the CryptoPanic API repo.

Typed Response Models

Instead of dealing with anonymous arrays returned by json_decode(), the SDK maps known response shapes into strictly typed objects. When you request a page of posts, you receive a PostsPage object containing an array of Post instances. Each Post exposes properties like title, source, votes, and publication dates parsed into DateTimeImmutable objects. This allows your IDE to provide accurate autocompletion and static analysis tools like PHPStan to catch errors before they reach production repo.

Safe and Immutable Design

Security and predictability are paramount when handling API tokens. The SDK ensures that your authentication token is never included in exception messages or data dumps. Furthermore, when the API returns pagination URLs, the SDK automatically redacts the token from them repo.

The core components, such as CryptoPanicConfig and PostsQuery, are designed as immutable value objects. When you need to request the next page or modify a filter, you use the with() method to create a new instance without mutating the original state. This functional approach eliminates side effects and makes your code easier to reason about repo.

Robust Error Handling and Retries

Network requests fail, and APIs enforce rate limits. cryptopanic-php abstracts these challenges with a rich exception hierarchy. Instead of catching generic HTTP errors, you can handle specific scenarios:

Situation Dedicated exception Practical response
Invalid or missing token UnauthorizedException Refresh or replace the credential without exposing it in application logs.
Plan-restricted endpoint ForbiddenException Adjust the workflow or verify account access before retrying.
Request quota exceeded RateLimitException Respect the available retryAfter guidance and slow down.

These explicit failure modes make it easier to implement intentional recovery paths rather than treating every unsuccessful request as the same generic error repo.

Moreover, the SDK includes configurable retry logic with exponential backoff. You can instruct the client to automatically retry transient failures like HTTP 429 (Too Many Requests) or 502 (Bad Gateway) without writing a custom retry loop repo.

Getting Started

Installing the package is as simple as running a Composer command. The SDK requires PHP 8.1+, ext-json, and ext-curl repo.

composer require tigusigalpa/cryptopanic-php
Enter fullscreen mode Exit fullscreen mode

Framework-Neutral Usage

If you are building a plain PHP worker or a Symfony service, you can initialize the client using environment variables. Keep your token secure in your environment:

export CRYPTOPANIC_AUTH_TOKEN="your-super-secret-token"
Enter fullscreen mode Exit fullscreen mode

Then, instantiate the client and fetch a page of posts filtered by specific currencies:

<?php

declare(strict_types=1);

use Tigusigalpa\CryptoPanic\CryptoPanicClient;
use Tigusigalpa\CryptoPanic\PostsQuery;
use Tigusigalpa\CryptoPanic\Enums\Filter;

$client = CryptoPanicClient::fromEnv();

$query = new PostsQuery(
    currencies: ['BTC', 'ETH'],
    filter: Filter::Rising,
    page: 1,
);

$page = $client->posts($query);

foreach ($page->results as $post) {
    printf("[%s] %s\n", $post->kind ?? 'unknown', $post->title ?? 'Untitled');

    if ($post->publishedAt !== null) {
        echo 'Published: ' . $post->publishedAt->format(DATE_ATOM) . PHP_EOL;
    }
}
Enter fullscreen mode Exit fullscreen mode

The PostsQuery object validates your parameters locally, ensuring you do not send malformed requests. It also uses backed enums for known filters and kinds, while remaining flexible enough to accept custom strings for forward compatibility repo.

First-Class Laravel Integration

While the SDK is framework-neutral, it shines particularly bright in Laravel applications. The package includes an auto-discovered service provider that registers the client as a singleton, merges configuration, and provides a convenient Facade repo.

After installation, you can publish the configuration file:

php artisan vendor:publish --tag=cryptopanic-config
Enter fullscreen mode Exit fullscreen mode

Add your credentials to your .env file:

CRYPTOPANIC_AUTH_TOKEN=your-token
CRYPTOPANIC_API_PLAN=growth
CRYPTOPANIC_TIMEOUT=15
CRYPTOPANIC_RETRY_ATTEMPTS=3
CRYPTOPANIC_RETRY_DELAY=1
Enter fullscreen mode Exit fullscreen mode

You can now inject the CryptoPanicClient directly into your controllers or use the Facade for rapid development:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Tigusigalpa\CryptoPanic\Enums\Filter;
use Tigusigalpa\CryptoPanic\Laravel\Facades\CryptoPanic;
use Tigusigalpa\CryptoPanic\PostsQuery;

class CryptoNewsController extends Controller
{
    public function index(): JsonResponse
    {
        $page = CryptoPanic::posts(new PostsQuery(
            currencies: ['SOL', 'ADA'],
            filter: Filter::Important,
        ));

        return response()->json($page->results);
    }
}
Enter fullscreen mode Exit fullscreen mode

The service provider defers network connections until you actually make a request, ensuring it does not impact your application's boot time repo.

Advanced Capabilities

The SDK is not limited to just fetching JSON posts. It provides comprehensive coverage of the CryptoPanic API surface.

Handling Unstable Schemas

Some API endpoints, like the Portfolio endpoint, do not have a strictly defined public schema. Instead of guessing domain fields and risking breakages when the API evolves, the SDK returns a PortfolioResponse where the raw property contains the decoded JSON. This treats the unstable endpoint as an integration boundary, allowing you to map the data into your own DTOs repo.

$portfolio = $client->portfolio();
// Inspect the raw array and map it to your application's needs
$data = $portfolio->raw;
Enter fullscreen mode Exit fullscreen mode

Raw RSS Access

If your application relies on XML feeds, the SDK provides dedicated methods for the RSS endpoints. Methods like postsRss() and newsRss() return an RSSResponse containing the raw XML body, allowing you to stream it directly or parse it with your preferred XML library repo.

$feed = $client->newsRss();
header('Content-Type: application/rss+xml');
echo $feed->body;
Enter fullscreen mode Exit fullscreen mode

Flexible Transports

By default, the SDK uses a lightweight cURL transport to minimize dependencies. However, if your application already standardizes on PSR-18 HTTP clients (like Guzzle), you can inject your preferred client and request factory repo.

use GuzzleHttp\Client;
use GuzzleHttp\Psr7\HttpFactory;
use Tigusigalpa\CryptoPanic\CryptoPanicClient;
use Tigusigalpa\CryptoPanic\CryptoPanicConfig;

$client = new CryptoPanicClient(
    config: CryptoPanicConfig::fromEnv(),
    psrClient: new Client(),
    requestFactory: new HttpFactory(),
);
Enter fullscreen mode Exit fullscreen mode

This flexibility ensures that cryptopanic-php plays nicely with your existing logging, middleware, and mocking strategies.

Navigating API Plans

It is important to note that the CryptoPanic API operates on a tiered plan system. Its public documentation labels the free Developer API plan as discontinued, so you should verify the current commercial details in your CryptoPanic account rather than assume free access is available api. Feature availability is determined by CryptoPanic, not by the SDK.

API capability Current plan note in the public API reference
portfolio() Listed for Growth and Enterprise plans.
size, with_content, and search Listed as Enterprise-gated parameters.
RSS responses Documented as returning 20 items regardless of API plan.

These constraints come from the API provider and may change; the package surfaces the response cleanly while preserving CryptoPanic as the authority for account entitlements repo.

The SDK validates obvious syntax locally but defers to CryptoPanic for account entitlements. If you attempt to use a feature outside your plan, the SDK will gracefully throw a ForbiddenException, allowing your application to handle the restriction cleanly repo.

Conclusion

Building applications around financial news requires reliability and precision. cryptopanic-php delivers both by abstracting the complexities of the CryptoPanic API behind a modern, strictly typed, and developer-friendly interface. Whether you are orchestrating background workers in plain PHP or building a rapid prototype in Laravel, this SDK provides the tools you need to succeed.

Stop writing boilerplate API wrappers and start focusing on your application's unique value. Check out the cryptopanic-php repository on GitHub, explore the source code, and give it a star if it saves you time on your next crypto project.

References

  1. repo

  2. api

Top comments (0)