Adding Execution Time to APIs in Laravel

Introduction

In any web application, monitoring performance is crucial for ensuring optimal user experience. One useful metric to track is the execution time of API requests. In this tutorial, we’ll learn how to add execution time to API responses in Laravel using middleware.

Prerequisites

Before we begin, make sure you have:

  • Basic familiarity with Laravel.
  • A Laravel development environment set up.

Step 1: Create the Middleware

First, let’s create a middleware that calculates and adds the execution time to API responses.

  1. Use the Laravel Artisan command to generate a new middleware named AddExecutionTime:
php artisan make:middleware AddExecutionTime
  1. Open the generated middleware file app/Http/Middleware/AddExecutionTime.php and implement the logic:
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class AddExecutionTime
{
    public function handle(Request $request, Closure $next)
    {
        $startTime = microtime(true);

        // Process the request and get the response
        $response = $next($request);

        $endTime = microtime(true);
        $executionTime = $endTime - $startTime;
        $formattedExecutionTime = number_format($executionTime, 3); // Format to 3 decimal places

        // Decode the original response content to an array
        $originalContent = json_decode($response->getContent(), true);

        // Add execution time to the response data
        $originalContent['seconds'] = $formattedExecutionTime;

        // Encode the array back to JSON and set it as the response content
        $response->setContent(json_encode($originalContent));

        return $response;
    }
}

Step 2: Register the Middleware

Next, register your middleware in Laravel’s HTTP Kernel.

  1. Open app/Http/Kernel.php and add your middleware to the api middleware group:
protected $middlewareGroups = [
    'web' => [
        // Other middleware...
    ],

    'api' => [
        'throttle:api',
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
        \App\Http\Middleware\AddExecutionTime::class,
    ],
];

Step 3: Test Your Middleware

Now, let’s test the middleware by making a sample API request.

  1. Make an API request, for example:
GET /api/example_endpoint
  1. Example response with execution time added:
{
  "data": [
    {
      "id": 1,
    },
    {
      "id": 2,
    },
    {
      "id": 3,
    }
  ],
  "errors": [],
  "status": "SUCCESS",
  "seconds": 0.019
}

Conclusion

Adding execution time to API responses provides valuable insight into request performance, aiding in debugging and optimizing your Laravel applications. By implementing this middleware, you enhance your ability to monitor and improve API responsiveness effectively.

Final Thoughts

Now that you’ve learned how to integrate execution time tracking into your Laravel APIs, extend this concept further by exploring additional middleware functionalities or integrating with logging systems for more comprehensive performance monitoring.

This blog post provides a practical guide with code examples to help readers implement execution time tracking in their Laravel APIs. Adjust the details and code snippets as needed to fit your specific use case and audience.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top