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:
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.
Auto-generated API documentation: Generate comprehensive API documentation including generating OpenAPI Specification, making it easier for developers to understand and consume your API.
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.
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.
Share requests: Easily share requests and responses with team members or stakeholders, facilitating collaboration and troubleshooting.
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
OR
Using the Laravel installer
You can install the Laravel installer using the following command
composer global require laravel/installer
Then create a new Laravel project using the following command
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:
- Install the Treblle package using Composer:
composer require treblle/treblle-laravel:^4.0
- Run the Treblle Artisan command to set up your account and obtain the necessary environment variables:
php artisan treblle:start
- 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
- 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,
- 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;
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);
});
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
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
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
That will create an Api resource controller for your Product model with all the necessary methods.
The
model
is located atapp/Models/Product.php
is responsible for interacting with the database.The
migration
is located atdatabase/migrations/2023_06_30_000000_create_products_table.php
is responsible for creating theproducts
table in the database.The
factory
is located atdatabase/factories/ProductFactory.php
is responsible for generating fake data for theproducts
table.The
seeder
is located atdatabase/seeders/DatabaseSeeder.php
is responsible for seeding theproducts
table with fake data.The
controller
is located atapp/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();
});
Run the migration:
php artisan migrate
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),
];
}
}
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();
}
}
To run the seeder, run the following command:
php artisan migrate:fresh --seed
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
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();
});
Running tests
php artisan test
Testing the API
php artisan serve
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)
Great article, Alpha!