Enhancing Your Laravel API with Treblle Platform
Tags: webdev, learning, laravel, tutorial
Published: 2023-06-25 07:12:49

## 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](https://docs.treblle.com/en/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](https://en.wikipedia.org/wiki/HTTP). 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:

```bash
composer create-project laravel/laravel treblle-laravel
```

OR

### Using the Laravel installer

You can install the Laravel installer using the following command

```bash
composer global require laravel/installer
```

Then create a new Laravel project using the following command

```bash
laravel new treblle-laravel
```

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:

```bash
composer require treblle/treblle-laravel:^4.0
```

2. Run the Treblle Artisan command to set up your account and obtain the necessary environment variables:

```bash
php artisan treblle:start
```

3. 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:

```dosini
TREBLLE_API_KEY=YOUR_API_KEY
TREBLLE_PROJECT_ID=YOUR_PROJECT_ID
```

4. 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

```php
'treblle' => \Treblle\Middlewares\TreblleMiddleware::class,
```

5. 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.

```php
// add the following line 👇 at the top of routes/api.php file
use App\Http\Controllers\Api\ProductController;
```

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

```php
// 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);
});
```

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:

```bash
php artisan vendor:publish --tag=treblle-config
```

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:

```bash
php artisan make:model Product -msf -R
```

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:

```bash
php artisan make:controller Api/ProductController --api --model=Product
```

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`

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

Run the migration:

```bash
php artisan migrate
```

### Model factory

Add the following fields to the `ProductFactory` class:

file: `database/factories/ProductFactory.php`

```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),
        ];
    }
}
```

### Model seeder

Add the following fields to the `ProductSeeder` class:

```php
<?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();
    }
}
```

To run the seeder, run the following command:

```bash
php artisan migrate:fresh --seed
```

## Testing the API

By default, Laravel comes with PHPUnit for testing. However you can use [Pest](https://pestphp.com/) instead.

### Generating Pest tests for your API

Generate a test for your Product API resource controller:

```bash
php artisan test:pest Api/ProductTest
```

## Writing tests

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

```php
<?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();
});
```

## Running tests

```bash
php artisan test
```

## Testing the API

```bash
php artisan serve
```

Open [Postman](https://www.postman.com/) or [Httpie](https://httpie.io/) 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.