Skip to main content

Automate SDK generation for Laravel APIs

Supported SDK languages:

TypeScript /
Javascript
Java /
Kotlin
PythonC#GoPHP

tip
  1. Before getting started make sure you have a liblab account and the liblab CLI installed.
  2. If you don't have an existing project but want to try out liblab then check out our standalone tutorials.

Providing an SDK for your API can significantly ease the development process for users, ensuring quicker integration and encouraging wider adoption due to the streamlined development experience.

In this doc you'll learn how to take your existing Laravel API and generate user-friendly SDKs for most major programming languages using the liblab SDK generator. After a short bit of setup you'll have a pipeline that will automatically generate SDKs for your API whenever you make changes.

Initializing the SDK

First, create a new directory to store your SDK. This directory should be separate from your existing project directory:

mkdir Laravel-sdk cd Laravel-sdk

And initialize your project to create a liblab.config.json file:

liblab init -y

Getting an OpenAPI Spec File

In order to auto-generate SDKs from a Laravel project you need an OpenAPI Spec File. The OpenAPI file contains information about your API, such as servers, paths, operations, parameters, responses, and security schemas.

Installing Scribe

This guide uses an automatic OpenAPI generator for Laravel called Scribe. It will automatically inspect your project's routes and controllers to generate the OpenAPI spec.

To install Scribe, run the following command:

composer require --dev knuckleswtf/scribe
Alternatives

There are also other tools available for generating OpenAPI specs in Laravel such as Swagger-PHP, and Laravel-OpenAPI.

Configuring Scribe

Once Scribe is installed, you need to publish its configuration file. Run the following command:

php artisan vendor:publish --tag=scribe-config

This will create a scribe.php file in your config directory, where you can customize the documentation settings. The following configuration options are available:

  • title: The title of your API documentation.
  • description: A short description of your API.
  • base_url: The base URL displayed in the docs.
  • routes: Specifies which routes should be included in the documentation. By default, Scribe includes routes with the api/* prefix.
  • openapi.enabled: Set this to true to enable OpenAPI spec generation.
  • auth: Configures authentication requirements for API requests.
  • logo: Defines a path to a custom logo for the documentation.
tip

Check the Scribe documentation to check all the available options and how to use them to configure the API general information

Here's an example of the configuration for the config/scribe.php file:

scribe.php
<?php

use Knuckles\Scribe\Extracting\Strategies;

return [
'title' => 'Your API',
'description' => 'Your API description.',
'base_url' => 'www.your-domain.com',

'routes' => [
[
'match' => [
'prefixes' => ['api/*'], // Ensure 'api' is listed here
'domains' => ['*'],
],
'include' => [

],
'exclude' => [],
],
],
'intro_text' => <<<INTRO
This documentation aims to provide all the information you need to work with our API.
INTRO
,
'openapi' => [
'enabled' => true,
],
];

Annotating Your Controllers

To generate an OpenAPI spec, you can add docblocks to your Laravel controllers. These docblocks provide metadata about the endpoints, parameters, request bodies, and responses. Here are the request parameter annotations available:

  • @group: Group related endpoints together in the documentation.
  • @queryParam: Defines a query parameter used in an API request.
  • @bodyParam: Defines a parameter in the request body.
  • @response: Defines an example API response.
Beyond the Basics

You can use Atributes instead of docblocks to add your annotations. Access the supported annotations page to check a detailed comparison between these methods and to access the complete list of available response annotations.

Here's an example of a hello controller with Scribe annotations that provides a greeting message for users:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

/**
* @group Greeting
*
* APIs for greeting users
*/
class HelloController extends Controller
{
/**
* Greet a user.
*
* This endpoint returns a greeting message with the provided name.
*
* @urlParam name string required The name of the user. Example: John
*
* @response 200 {
* "message": "Hello, John!"
* }
*
* @param string $name
* @return \Illuminate\Http\JsonResponse
*/
public function greet(string $name)
{
return response()->json([
'message' => "Hello, $name!"
], 200);
}
}

Take it one step at a time

You don't need to annotate every view at once. You can start by annotating a single view or even just part of it (e.g., the 200 response) to get an understanding of annotations.

Generating the OpenAPI Spec File

Once you have added annotations to your controllers, you can generate the OpenAPI spec using Scribe. Run the following command:

php artisan scribe:generate

This command will scan the app directory for annotations and generate the OpenAPI specification in YAML format. The YAML file will be available at public/docs/openapi.yaml.

Creating an Endpoint to Serve the Spec

By default, public/docs/openapi.yaml is just a static file in Laravel’s public/ directory, and Laravel’s built-in server doesn't serve it directly unless routed.

To make the OpenAPI file accessible via an API endpoint, add this route to routes/api.php:

routes/api.php
Route::get('/openapi', function () {
return response()->file(public_path('docs/openapi.yaml'));
});

Complete Example

Putting the above steps together produces a complete example of generating an Openapi spec in a Laravel framework using Scribe:

<?php

use Knuckles\Scribe\Extracting\Strategies;

return [
'title' => 'Your API',
'description' => 'Your API description.',
'base_url' => 'www.your-domain.com',

'routes' => [
[
'match' => [
'prefixes' => ['api/*'], // Ensure 'api' is listed here
'domains' => ['*'],
],
'include' => [

],
'exclude' => [],
],
],
'intro_text' => <<<INTRO
This documentation aims to provide all the information you need to work with our API.
INTRO
,
'openapi' => [
'enabled' => true,
],
];
Click to see the OpenAPI spec example
  openapi: 3.0.3
info:
title: 'Your API'
description: 'Your API description'
version: 1.0.0
servers:
-
url: www.helloapi.com
paths:
/api/openapi:
get:
summary: ''
operationId: getApiOpenapi
description: ''
parameters: []
responses:
200:
description: ''
content:
text/plain:
schema:
type: string
example: ''
tags:
- Endpoints
security: []
'/api/hello/{name}':
get:
summary: 'Greet a user.'
operationId: greetAUser
description: 'This endpoint returns a greeting message with the provided name.'
parameters: []
responses:
200:
description: ''
content:
application/json:
schema:
type: object
example:
message: 'Hello, John!'
properties:
message:
type: string
example: 'Hello, John!'
tags:
- Greeting
security: []
parameters:
-
in: path
name: name
description: ''
example: incidunt
required: true
schema:
type: string
tags:
-
name: Endpoints
description: ''
-
name: Greeting
description: "\nAPIs for greeting users"

Copy Your Spec

Once the configuration is complete, you can generate the OpenAPI spec file. Run your Laravel development server:

php artisan serve

To view your OpenAPI spec, navigate to the /api/openapi endpoint on your server (e.g., http://localhost:8000/api/openapi).

Now that your openapi.json file is generated, you're ready to proceed. Save your openapi.json file to the liblab project directory you created during the initialization step. This is typically something like:

cd ../Laravel-sdk curl -o openapi.yaml http://127.0.0.1:8000/docs/openapi.yaml

Configuring liblab

Now you'll need to make some minor updates to your liblab.config.json file in your Laravel-sdk folder:

  1. Point the specFilePath parameter to the location of your OpenAPI spec file (ex. ./openapi.json).
  2. Specify the baseUrl of your API. This is the URL that the SDK will use to make requests to your API.

The top of the file should then looks something like this:

{
"sdkName": "Laravel-sdk",
"apiVersion": "1.0.0",
"apiName": "Laravel-api",
"specFilePath": "./openapi.json",
"baseUrl": "http://localhost:PORT",
"languages": [
"go",
"java",
"python",
"typescript",
"csharp",
"php"
],
"auth": [
"bearer"
]
}
note

liblab's SDK generator supports many more advanced URL and environment configuration options than the basic configuration shown here.

Explore the configuration documentation to discover all the available settings and enhancements or review the SDK customization options for tailored adjustments.

Generate the SDK

info

During build you might see warnings about the OpenAPI spec. These are often minor issues that can be fixed later.

Now that you have an OpenAPI spec file and have finished setting the liblab.config.json file, it's time to generate our SDK:

liblab build -y

The CLI will validate the OpenAPI spec and notify you about any issues with it or the liblab.config.json.

The output will look something like this:

✓ No issues detected in the liblab config file.

No hooks found, SDKs will be generated without hooks.

⚠ Validation succeeded with warnings

Created /Users/username/projects/Laravel-sdk/output/api-schema-validation.json with the full linting results

Next you'll see the builds started and once they're done you'll see a message like this:

Your SDKs are being generated. Visit the liblab portal (https://app.liblab.com/apis/Laravel-sdk/builds/1234) to view more details on your build(s). ✓ C# built ✓ Go built ✓ Java built ✓ PHP built ✓ Python built ✓ TypeScript built ✓ Generate package-lock.json for TypeScript Successfully generated SDKs for Python, Java, Go, TypeScript, C#, PHP. ♡ You can find them inside: /Users/username/projects/Laravel-sdk/output

If we go inside the output directory, we will see a directory for each of our SDKs:

ls output/     api-schema-validation.json go php typescript     csharp java python

Try out your SDK

Environment Setup

The following instructions assume you have already set up the respective development environment for the language you are testing. If necessary refer to each language's official documentation before proceeding.

Learn more about the language versions liblab generated SDKs support.

note

The generated SDKs are intended to be deployed to package managers for end users. The instructions below to test your SDK locally will differ from user-facing instructions.

cd output/typescript/examples
npm run setup
npm run start

Next Steps

Now that you've packaged your SDKs you can learn how to integrate them with your CI/CD pipeline and publish them to their respective package manager repositories.

We currently have guides for: