APItoolkit full color logo
Sign Up

Laravel SDK Guide

To integrate your Laravel application with APItoolkit, you need to use this SDK to monitor incoming traffic, aggregate the requests, and then send them to APItoolkit's servers. Kindly follow this guide to get started and learn about all the supported features of APItoolkit's Laravel SDK.


Prerequisites

  • Ensure you have already completed the first three steps of the onboarding guide.
  • APItoolkit uses the Laravel cache to prevent reinitializing the SDK for each request. So, ensure you have Laravel cache set up in your application.

Installation

Kindly run the command below to install the SDK:

composer require apitoolkit/apitoolkit-laravel

Configuration

First, add the APITOOLKIT_KEY environment variable to your .env file, like so:

APITOOLKIT_KEY={ENTER_YOUR_API_KEY_HERE}

APITOOLKIT_DEBUG=false
APITOOLKIT_TAGS="environment: production, region: us-east-1"
APITOOLKIT_SERVICE_VERSION=v2.0

Next, register the middleware in the app/Http/Kernel.php file under the correct middleware group (e.g., api) or at the root, like so:

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
  protected $middlewareGroups = [
    'api' => [
      // Other middleware here...
      \APIToolkit\Http\Middleware\APIToolkit::class, // Initialize the APItoolkit client
    ],
  ];
}

Alternatively, if you want to monitor specific routes, you can register the middleware, like so:

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
  protected $routeMiddleware = [
    // Other middleware here...
    'apitoolkit' => \APIToolkit\Http\Middleware\APIToolkit::class,
  ];
}

Then you can use the apitoolkit middleware in your routes like so:

Route::get('/', function () {
  return response()->json([
    'message' => 'Welcome to your new application!'
  ]);
})->middleware('apitoolkit');

In the configuration above, only the APITOOLKIT_KEY option is required, but you can add the following optional fields:

OptionDescription
APITOOLKIT_DEBUGSet to true to enable debug mode.
APITOOLKIT_TAGSA list of defined tags for your services (used for grouping and filtering data on the dashboard).
APITOOLKIT_SERVICE_VERSIONA defined string version of your application (used for further debugging on the dashboard).
APITOOLKIT_REDACT_HEADERSA list of HTTP header keys to redact.
APITOOLKIT_REDACT_REQUEST_BODYA list of JSONPaths from the request body to redact.
APITOOLKIT_REDACT_RESPONSE_BODYA list of JSONPaths from the response body to redact.

Tip

The {ENTER_YOUR_API_KEY_HERE} demo string should be replaced with the API key generated from the APItoolkit dashboard.

Redacting Sensitive Data

If you have fields that are sensitive and should not be sent to APItoolkit servers, you can mark those fields to be redacted (the fields will never leave your servers).

To mark a field for redacting via this SDK, you need to add some additional environmental variables to the .env file with paths to the fields that should be redacted. There are three variables you can provide to configure what gets redacted, namely:

  1. APITOOLKIT_REDACT_HEADERS: A list of HTTP header keys.
  2. APITOOLKIT_REDACT_REQUEST_BODY: A list of JSONPaths from the request body.
  3. APITOOLKIT_REDACT_RESPONSE_BODY: A list of JSONPaths from the response body.


JSONPath is a query language used to select and extract data from JSON files. For example, given the following sample user data JSON object:

{
  "user": {
    "name": "John Martha",
    "email": "[email protected]",
    "addresses": [
      {
        "street": "123 Main St",
        "city": "Anytown",
        "state": "CA",
        "zip": "12345"
      },
      {
        "street": "123 Main St",
        "city": "Anytown",
        "state": "CA",
        "zip": "12345"
      }
    ],
    "credit_card": {
      "number": "4111111111111111",
      "expiration": "12/28",
      "cvv": "123"
    }
  }
}

Examples of valid JSONPath expressions would be:

JSONPathDescription
$.user.addresses[*].zipIn this case, APItoolkit will replace the zip field in all the objects of the addresses list inside the user object with the string [CLIENT_REDACTED].
$.user.credit_cardIn this case, APItoolkit will replace the entire credit_card object inside the user object with the string [CLIENT_REDACTED].

Tip

To learn more about JSONPaths, please take a look at the official docs or use this JSONPath Evaluator to validate your JSONPath expressions.

You can also use our JSON Redaction Tool to preview what the final data sent from your API to APItoolkit will look like, after redacting any given JSON object.


Here's an example of what the .env file would look like with redacted fields:

APITOOLKIT_REDACT_HEADERS="Content-Type, Authorization, HOST"
APITOOLKIT_REDACT_REQUEST_BODY="$.user.email, $.user.addresses"
APITOOLKIT_REDACT_RESPONSE_BODY="$.users[*].email, $.users[*].credit_card"

Note

  • The APITOOLKIT_REDACT_HEADERS variable expects a list of case-insensitive headers as strings.
  • The APITOOLKIT_REDACT_REQUEST_BODY and APITOOLKIT_REDACT_RESPONSE_BODY variables expect a list of JSONPaths as strings.
  • The list of items to be redacted will be applied to all endpoint requests and responses on your server.

Error Reporting

With APItoolkit, you can track and report different unhandled or uncaught errors, API issues, and anomalies at different parts of your application. This will help you associate more detail and context from your backend with any failing customer request.

To report all uncaught errors and service exceptions that happened during a web request, modify your Laravel Exceptions handler, passing in the error and the request as arguments, like so:

<?php

namespace App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use APIToolkit\APIToolkitLaravel;
use Throwable;

class Handler extends ExceptionHandler
{
  protected $dontReport = [];

  public function register()
  {
    $this->reportable(function (Throwable $e) {
      // Report the error to APItoolkit
      $request = request();
      APIToolkitLaravel::reportError($e, $request);
    });
  }
}

To manually report specific errors at different parts of your application, use the reportError method of the APIToolkitLaravel class, passing in the error and the request as arguments, like so:

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use APIToolkit\APIToolkitLaravel;

Route::get('/user', function (Request $request) {
  try {
    // Simulate a custom user error
    throw new Exception("Custom user error");

    // This line will not execute if an exception is thrown
    return response()->json(["hello" => "world"]);
  } catch (Exception $e) {
    // Report the error to APItoolkit
    APIToolkitLaravel::reportError($e, $request);

    // Return a JSON response with the error message
    return response()->json(["error" => $e->getMessage()]);
  }
});

Monitoring Outgoing Requests

Outgoing requests are external API calls you make from your API. By default, APItoolkit monitors all requests users make from your application and they will all appear in the API Log Explorer page. However, you can separate outgoing requests from others and explore them in the Outgoing Integrations page, alongside the incoming request that triggered them.

To monitor outgoing HTTP requests from your application, use the observeGuzzle method of the APIToolkitLaravel class, passing in the $request and $options object, like so:

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use APIToolkit\APIToolkitLaravel;

Route::get('/user', function (Request $request) {
  $options = [
    "pathWildCard" => "/repos/{owner}/{repo}",
    "redactHeaders" => ["content-type", "Authorization", "HOST"],
    "redactRequestBody" => ["$.user.email", "$.user.addresses"],
    "redactResponseBody" => ["$.users[*].email", "$.users[*].credit_card"]
  ];
  $guzzleClient = APIToolkitLaravel::observeGuzzle($request, $options);
  $responseFromGuzzle = $guzzleClient->request('GET', 'https://api.github.com/repos/apitoolkit/apitoolkit-laravel?foobar=123');
  $response = $responseFromGuzzle->getBody()->getContents();

  return $response;
});

The $options associative array accepts the following optional fields:

OptionDescription
pathWildCardThe url_path string for URLs with path parameters.
redactHeadersA list of HTTP header keys to redact.
redactResponseBodyA list of JSONPaths from the request body to redact.
redactRequestBodyA list of JSONPaths from the response body to redact.

Explore the Laravel SDK