PHP Laravel Framework

Enterprise Laravel in 10 steps

Introduction

Malik Sharfo
4 min readNov 25, 2021

--

In this 10-part series we will build an enterprise Laravel API.

A link to the github repository used, will be provided at the end of this article.

What does an enterprise API even mean?

Some readers might have strong beliefs on certain design principles. We will not enter age-old debates arguing for one paradigm over another. We won’t even make strong arguments for our positions. We will take it for granted that any enterprise API should:

  1. Autogenerate documentation.
  2. Decouple the API from the database structure.
  3. Have flexible authentication on authorization.
  4. Have excellent testing, even of the documentation.

Every article has its own commit in this repo. You will notice that we are just using one model and one table so that every commit is super-focused on API mechanics.

What is OpenAPI?

OpenAPI Specification, which was formerly known as Swagger Specification, is an API description format for RESTful APIs, or in shorter terms REST APIs.

APIs who have the ability to describe their own structure, is the root to all greatness in OpenAPI.

There are many great advantages of using OpenAPI, but we will rather reference OpenAPIs own great documentation, of why to use OpenAPI.

Swagger and OpenAPI is the same, but not really the same.

  • OpenAPI is the specification itself, which was formerly known as Swagger specification.
  • Swagger is the tools used in the implementation of OpenAPI.

Swagger PHP

Swagger is a library that allows you to use annotations to generate OpenAPI documentation from already existing code, or create manually, for PHP.

The objective of swagger-php is to generate an openapi.jsonusing phpdoc annotations.

It is not obligatory to place all of your annotations inside one big @OA\OpenApi() annotation block, but it is better to distribute them throughout your codebase.

This is because swagger-php will scan your project and merge all annotations into one @OA\OpenApi annotation.

With newer versions of PHP, PHP version 7.4 and above, you can now have typed properties, just like you would know from other programming languages, you can now define what types your variables are of, as shown in the below, yet simple, example.

In this series we will show you how to annotate your code so that OpenAPI can detect these variables. Follow along our articles to get an understanding of how to achieve that.

use App\Models\User;class MyClass 
{
public User $user;
public string $name;
public int $age;
public array $arr;
}

Getting started with Swagger

To be able to use Swagger-PHP to help generate your OpenAPI specs, you first need to have Swagger-PHP installed in your project.

The recommended way to add swagger-php to your project is with Composer.
You can install Swagger with Composer by typing the following in your preferred terminal which is located to the root of your project:

composer require zircote/swagger-php 

For more information about zircote follow this reference.

Start using the OpenAPI annotations

Under app/Http/Controllers/UserController.phpwe start annotating our UserController class.

use App\Models\User;<?php
/**
* @OA\Swagger(
* schemes={“https”},
* host=”mywebsite.com”,
* basePath=””,
* @OA\Info(
* version=”1.0.0",
* title=”My Website”,
* description=”Put Markdown Here [a Link](https://www.google.com)”,
* @OA\Contact(
* email=”my@email”
* ),
* ),
* )
*/
class UserController extends Controller
{
/**
* @OA\Get(path=”/api/users”, description=”Get all users”, operationId=””,
* @OA\Response(response=200, description=”OK”,
* @OA\JsonContent(type=”string”)
* ),
* @OA\Response(response=401, description=”Unauthorized”),
* @OA\Response(response=404, description=”Not Found”)
* )
*/
public function index(Request $request)
{
return User::all();
}
}

The @OA\Get()describes the operation available on the path we want to reach. All Laravel routes are defined in your route files, which you can find located in the routesdirectory. Routes defined inside the routes/api.phpfile are nested within a route group named RouteServiceProviderwhich can be found under app/Providers/RouteServiceProvider.php. And since our UserController is called by our routes/api.php file, we have prepended it with /api .

@OA\Response() describes the possible HTTP status code that can be expected returned from executing the given operation.

The @OA\MediaTypeis used to describe the content, and since Laravel returns Json by default from anything served via routes/api.php, we use @OA\JsonContent.

As of right now there is a mismatch in the type of JsonContent and the return statement in the index function, which will be fixed in the later parts.

Generating the Swagger File

To generate the Swagger file, navigate to routes/api.php and write like the below code. What this does is, that it scans all the paths that you provide it and converts it to Json format, and in our case we are serving it app_path() which contains everything that is located inside the appfolder, this means that only the appfolders contents gets scanned and converted to Json format.

If you are serving this on a domain, for example localhost , you can open localhost/api/swagger.json in your browser and verify that you are getting Json.

use OpenApi\Generator;Route::get('/swagger.json', function () {
Generator::scan([ app_path(), ])->toJson()
});

In this article we have taken the first, and smallest step possible, towards an enterprise API. Stay tuned for more articles to come.

Github repository for this article can be found here.

--

--