Building a Micro Markdown API App with Lumen

Share this article

If you’ve been using Laravel for a while, you know that it sometimes feels a little heavy for a small application or service. For that same purpose, Taylor, the creator of Laravel built Lumen. A small micro-framework built on top of Laravel Illuminate components, it doesn’t load all the components by default like Eloquent, Blade, Middleware, etc, remaining light as it boots up. We will explore all of that this short tutorial.

Lumen Header

Why Lumen?

If you’re already a Laravel user, you may be in love with Laravel’s syntax and shortcuts. But, when working on just a small application, you don’t want to have a full stack framework with all the packages wired up. Lumen provides a good starting point for your small application, stripping out all the parts that you probably won’t need.

What We’re Building

To illustrate a practical use case for the micro framework, we will be creating a Markdown parser API application where the user can submit a Markdown text and get back the parsed content as JSON. I will be using the league/commonmark package from the PHP League. You can check the final result on Github.

Installation

If you’re creating new applications often, you can use the global installer (composer global require "laravel/lumen-installer=~1.0") and take advantage of short syntax like lumen new my-project, or you can use composer to create a new project with composer create-project laravel/lumen my-project --prefer-dist. You can read more about the installation process in the documentation.

After Lumen is installed, you can go ahead and require the commonmark package using composer require league/commonmark. Visit the documentation for more info about it.

Folder Structure

The first thing that you’ll notice after installing Lumen is the folder structure. A lot of things are stripped out, like the config, database and resources folders, which can be brought back when necessary using some scaffolding commands, or manually.

Lumen provides you with the php artisan make command to help you scaffold the missing folders. If you want to work with view templates, you can run php artisan make views to create the resources/views folder for your templates. The available commands can be found in the Laravel\Lumen\Console\Commands\MakeCommand class.

  • php artisan make foundation: scaffold the resources and database folders.
  • php artisan make resources: scaffold the resources folder.
  • php artisan make database: scaffold the database folder.
  • php artisan make lang: scaffold the resources/lang folder.
  • php artisan make views: scaffold the resources/views folder.

Parsing Markdown

// app/Http/routes.php

$app->get('/parse', 'App\Http\Controllers\MarkdownController@parse');
// app/Http/Controllers/MarkdownController.php

public function parse(Request $request, CommonMarkConverter $parser)
{
    $text = $request->get('text');
    $result = $parser->convertToHtml($text);

    return ['html' => $result];
}

After the user submits the Markdown text to our /parse endpoint, we will retrieve the content from the request object and parse it. You noticed that we took advantage of the service container type hinting to resolve the markdown and request objects. If you decide to use Facades (Request::get('text')), just make sure to tell your application to load them (see next section).

HTML result

Facades, Eloquent and Middleware

Because Facades, Eloquent ORM and Middleware are commonly used in Laravel applications, we have them added by default inside our bootstrap/app.php file and we only need to uncomment them before starting to use them.

// bootstrap/app.php

$app->withFacades();
$app->withEloquent();
$app->middleware([
    //...
]);

If your application needs to include other services, you can use the $app->register('AppServiceProvider'); syntax to register the list of providers.

Generally speaking, most of the Lumen parts work the same as in Laravel, they are either not loaded by default or need to be installed and wired into the application. For example, you can use the Laravel FileSystem package as usual (Storage::disk('local')->put('file.txt', 'Content here');) and it will work as expected. However, if you want to work with Rackspace, you need to pull the league/flysystem-rackspace package using Composer and specify your credentials inside the .env file.

Using the API

After our service is up and running, we can consume our API using Guzzle or any other package or method you prefer.

$client = new GuzzleHttp\Client();
$response = $client->get('http://vaprobash.dev/parse', [
    'query' => ['text' => file_get_contents('myFile.md')]
])->json();
$html = $response->html;

If a part of your service is getting a lot of traffic, it makes sense to have light micro-framework to handle this part of the application without having to load all the domain login and packages to complete a simple task.

Conclusion

Lumen will bring back some Laravel fans who don’t like to use the full framework for small tasks. You can check the documentation for more information. If you’ve already tried Lumen, I would love to know your first impressions of it, and about the advantages you think it has over the other micro frameworks?

Frequently Asked Questions (FAQs) about Building a Micro Markdown API App with Lumen

What is the main difference between Laravel and Lumen?

Laravel and Lumen are both PHP frameworks, but they are designed for different types of projects. Laravel is a full-stack framework that includes everything you need to build a complete web application, including routing, database management, and user authentication. On the other hand, Lumen is a micro-framework that is designed for building APIs and microservices. It is a stripped-down version of Laravel, with many of the same features but a much smaller footprint. This makes it faster and more efficient for handling small, specific tasks.

How do I install Lumen?

To install Lumen, you need to have Composer installed on your system. Composer is a tool for dependency management in PHP. Once you have Composer installed, you can install Lumen by running the following command in your terminal: composer global require "laravel/lumen-installer". This will install the Lumen installer globally on your system. You can then create a new Lumen project by running lumen new project-name.

How do I create routes in Lumen?

In Lumen, you can create routes by adding them to the routes/web.php file. Each route consists of a URI and a closure or controller method that should be executed when the route is accessed. For example, to create a route for the URI /users, you would add the following code to your routes/web.php file: $router->get('/users', 'UserController@index');. This code specifies that when the /users URI is accessed, the index method of the UserController should be executed.

How do I connect to a database in Lumen?

To connect to a database in Lumen, you need to configure your database settings in the .env file. This file is located in the root directory of your Lumen project. You can specify the type of database you are using (MySQL, PostgreSQL, SQLite, etc.), the host, the database name, the username, and the password. Once you have configured your database settings, you can use the DB facade or the database helper function to interact with your database.

How do I handle errors in Lumen?

Lumen comes with built-in error handling that makes it easy to handle different types of errors. By default, Lumen will convert all exceptions into HTTP responses. You can customize how exceptions are handled by modifying the render method in the app/Exceptions/Handler.php file. You can also use the report method in this file to log exceptions or send them to an external service.

How do I test my Lumen application?

Lumen provides several tools for testing your application. You can use the phpunit command to run your tests. Lumen also includes a TestCase class that you can extend to create your own tests. This class provides methods for making HTTP requests to your application and examining the resulting output.

How do I deploy my Lumen application?

There are many ways to deploy a Lumen application. One common method is to use a platform as a service (PaaS) provider like Heroku or AWS. These services handle much of the deployment process for you, including server management, database setup, and scaling. You can also deploy your Lumen application on a virtual private server (VPS) or a dedicated server if you prefer to have more control over the deployment process.

Can I use Laravel packages in Lumen?

Yes, you can use most Laravel packages in Lumen. However, because Lumen is a stripped-down version of Laravel, some packages may not work if they rely on features that are not included in Lumen. To use a Laravel package in Lumen, you need to register the service provider for the package in your bootstrap/app.php file.

How do I authenticate users in Lumen?

Lumen does not include the same authentication features as Laravel, but it does provide a simple way to authenticate users using API tokens. You can generate a unique token for each user and include it in the headers of your API requests. You can then use the auth middleware to check the token and authenticate the user.

How do I handle CORS in Lumen?

Cross-Origin Resource Sharing (CORS) is a security feature that restricts how resources on a web page can be requested from another domain. To handle CORS in Lumen, you can use the fruitcake/laravel-cors package. This package provides a middleware that you can use to add the necessary CORS headers to your responses.

Younes RafieYounes Rafie
View Author

Younes is a freelance web developer, technical writer and a blogger from Morocco. He's worked with JAVA, J2EE, JavaScript, etc., but his language of choice is PHP. You can learn more about him on his website.

apiBrunoSframeworklaravellumenOOPHPPHPsilexslim
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week
Loading form