DEV Community

Alpha Olomi
Alpha Olomi

Posted on

Enhancing Your Laravel API with Treblle Platform

Welcome

In this blog post, we will explore features of Treblle, how to integrate Treblle into your Laravel API, enabling you to gain real-time insights, improve the quality of your API, and enhance the overall development process.

What is Treblle?

Treblle is a powerful API platform that simplifies the monitoring, documentation, analytics, and management of your APIs. In this blog post, we will explore how to integrate Treblle into your Laravel API, enabling you to gain real-time insights, improve the quality of your API, and enhance the overall development process.

Who is this tutorial for?

This tutorial is for developers who are building APIs using Laravel. It is also for developers who are responsible for monitoring, analyzing, and managing APIs. Or you are involved in building and maintaining APIs on a daily basis, Treblle is a valuable tool for you.

Integrations

Treblle provides official SDKs for various programming languages and frameworks. Not just Laravel. If you're using a different framework or language than Laravel, you can still integrate Treblle into your API. Here are some of the official Treblle SDKs:

  • PHP: Laravel, Symfony, Lumen
  • JavaScript: Node.js, Sails.js, AdonisJS, Fastify, Directus, Strapi, Express, Nest, Koa
  • Others: .NET, Go, .NET Core, Django, Rails, Spring

Learn more at treblle integrations docs page.

These SDKs enable you to seamlessly connect your API codebase to Treblle, leveraging the features and benefits offered by the platform.

Introduction

Treblle is a powerful API platform that simplifies the monitoring, documentation, analytics, and management of your APIs. In this blog post, we will explore how to integrate Treblle into your Laravel API, enabling you to gain real-time insights, improve the quality of your API, and enhance the overall development process.

Features of Treblle API Platform

By integrating Treblle into API, you gain access to a range of powerful features, including:

  1. Real-time API monitoring and logging: Monitor and track every request and response in real-time, gaining valuable insights into the performance and behavior of your API.

  2. Auto-generated API documentation: Generate comprehensive API documentation including generating OpenAPI Specification, making it easier for developers to understand and consume your API.

  3. API analytics: Measure key metrics such as response time, request load size, and more, enabling you to optimize the performance of your API and identify potential bottlenecks.

  4. API quality scoring: Treblle calculates an API score based on best practices for performance, quality, and security, helping you ensure that your API meets industry standards.

  5. Share requests: Easily share requests and responses with team members or stakeholders, facilitating collaboration and troubleshooting.

  6. Error reporting: Treblle captures and reports errors that occur within your API, enabling you to identify and resolve issues promptly.

Who is Treblle for?

Treblle is designed to cater to both technical and non-technical roles that work with APIs. Whether you are responsible for monitoring, analyzing, and managing APIs, or you are involved in building and maintaining APIs on a daily basis, Treblle is a valuable tool for you.

HTTP APIs, or Application Programming Interfaces, serve as the communication bridge between different software systems using the HTTP protocol. They are extensively used in web applications, mobile apps, and system integrations. Treblle simplifies the API lifecycle tasks such as administration, documentation, support, debugging, and monitoring, allowing you to focus on building robust APIs.

How Treblle Works

Create a new Laravel project using the following command:

composer create-project laravel/laravel treblle-laravel
Enter fullscreen mode Exit fullscreen mode

OR

Using the Laravel installer

You can install the Laravel installer using the following command

composer global require laravel/installer
Enter fullscreen mode Exit fullscreen mode

Then create a new Laravel project using the following command

laravel new treblle-laravel
Enter fullscreen mode Exit fullscreen mode

Integrating Treblle into your Laravel API is a straightforward process. After creating a Treblle account and obtaining your API key and project ID, follow these steps:

  1. Install the Treblle package using Composer:
composer require treblle/treblle-laravel:^4.0
Enter fullscreen mode Exit fullscreen mode
  1. Run the Treblle Artisan command to set up your account and obtain the necessary environment variables:
php artisan treblle:start
Enter fullscreen mode Exit fullscreen mode
  1. Update your .env file with the provided API key and project ID:

Going forward ensure that you have created a Treblle account and obtained your API key and project ID.

You can find your API key and project ID in the Treblle dashboard. And then update your .env file with the provided API key and project ID:

TREBLLE_API_KEY=YOUR_API_KEY
TREBLLE_PROJECT_ID=YOUR_PROJECT_ID
Enter fullscreen mode Exit fullscreen mode
  1. Register the Treblle middleware in the file app/Http/Kernel.php by adding to the following line to the $middlewareAliases property(array):

file: app/Http/Kernel.php location: $middlewareAliases property

'treblle' => \Treblle\Middlewares\TreblleMiddleware::class,
Enter fullscreen mode Exit fullscreen mode
  1. Apply the Treblle middleware to your API routes in

In the file routes/api.php, add the following line at the top of the file:

This will apply the Treblle middleware to all the routes in the file.

// add the following line ๐Ÿ‘‡ at the top of routes/api.php file
use App\Http\Controllers\Api\ProductController;
Enter fullscreen mode Exit fullscreen mode

file: routes/api.php location: top of the file

// Add the following lines ๐Ÿ‘‡ at the bottom of routes/api.php file
use App\Http\Controllers\Api\ProductController;

// Add the following lines ๐Ÿ‘‡ after all the routes in routes/api.php file
Route::middleware(['treblle'])->group(function () {
    // This will apply the Treblle middleware to products routes
    // For new projects, you can use the following line to generate the routes
    // for the ProductController
    Route::apiResource('products', ProductController::class);
});
Enter fullscreen mode Exit fullscreen mode

With these steps, Treblle is seamlessly integrated into your Laravel API.

Configuration Options

Treblle offers various configuration options to customize your integration. To modify the configuration, you can publish the Treblle configuration file using the following command:

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

The configuration file config/treblle.php allows you to customize options such as masked fields. Treblle automatically masks sensitive information, such as passwords, credit card numbers, and API keys. To customize the masked fields, update the masked_fields array in the configuration file.

Additionally, you can configure Treblle using environment variables. For example, you can define the environments in which Treblle should not log by setting the TREBLLE_IGNORED_ENV variable in your .env file.

Setting Up your Product model

Let's create a Product model and a corresponding controller to demonstrate how Treblle works. Using the Laravel Artisan command, we can create a model and a controller.. We will use the following command to create a Product model:

php artisan make:model Product -msf -R
Enter fullscreen mode Exit fullscreen mode

The -msf options will create a migration, seeder, and factory for the Product model. The -R option will create a request class for the Product model.

To generate a controller for the Product model its simple as running the following command:

php artisan make:controller Api/ProductController --api --model=Product
Enter fullscreen mode Exit fullscreen mode

That will create an Api resource controller for your Product model with all the necessary methods.

  • The model is located at app/Models/Product.php is responsible for interacting with the database.

  • The migration is located at database/migrations/2023_06_30_000000_create_products_table.php is responsible for creating the products table in the database.

  • The factory is located at database/factories/ProductFactory.php is responsible for generating fake data for the products table.

  • The seeder is located at database/seeders/DatabaseSeeder.php is responsible for seeding the products table with fake data.

  • The controller is located at app/Http/Controllers/Api/ProductController.php is responsible for handling the incoming requests and returning the appropriate responses.

Migration

Add the following fields to the products table:

file: database/migrations/2023_06_30_000000_create_products_table.php

Schema::create('products', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->string('description');
    $table->integer('price');
    $table->timestamps();
});
Enter fullscreen mode Exit fullscreen mode

Run the migration:

php artisan migrate
Enter fullscreen mode Exit fullscreen mode

Model factory

Add the following fields to the ProductFactory class:

file: database/factories/ProductFactory.php

<?php

namespace Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;

/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Product>
 */
class ProductFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     */
    public function definition(): array
    {
        return [
            'name' => fake()->word(3),
            'description' => fake()->sentence(10),
            'price' => fake()->numberBetween(1000, 100_000),
        ];
    }
}
Enter fullscreen mode Exit fullscreen mode

Model seeder

Add the following fields to the ProductSeeder class:

<?php

namespace Database\Seeders;

use App\Models\Product;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

class ProductSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        Product::factory()->count(10)->create();
    }
}
Enter fullscreen mode Exit fullscreen mode

To run the seeder, run the following command:

php artisan migrate:fresh --seed
Enter fullscreen mode Exit fullscreen mode

Testing the API

By default, Laravel comes with PHPUnit for testing. However you can use Pest instead.

Generating Pest tests for your API

Generate a test for your Product API resource controller:

php artisan test:pest Api/ProductTest
Enter fullscreen mode Exit fullscreen mode

Writing tests

Replace the contents of tests/Feature/Api/ProductTest.php with the following code:

<?php

use App\Models\Product;

it('can list products', function () {
    $response = $this->getJson('/api/products');

    $response->assertOk();
});

it('can view a product', function () {
    $product = Product::factory()->create();

    $response = $this->getJson("/api/products/{$product->id}");

    $response->assertOk();
});
Enter fullscreen mode Exit fullscreen mode

Running tests

php artisan test
Enter fullscreen mode Exit fullscreen mode

Testing the API

php artisan serve
Enter fullscreen mode Exit fullscreen mode

Open Postman or Httpie or any client you use and create a new request to http://localhost:8000/api/products and send a GET request.

Opening the Treblle dashboard, you should see the request you just made.

Conclusion

Integrating Treblle into your Laravel API empowers you with powerful monitoring, documentation, analytics, and management capabilities. By gaining real-time insights, improving the quality of your API, and leveraging the range of features Treblle provides, you can streamline your API development process and ensure the optimal performance of your API. Start integrating Treblle today and experience the benefits firsthand.

Top comments (1)

Collapse
 
harshreality profile image
Harsha

Great article, Alpha!