10 Guide REST API With Lumen (cloudways.com) (web Page)

User Manual:

Open the PDF directly: View PDF PDF.
Page Count: 9

Lumen is a micro-framework built on top of Laravel. The framework is ideal for
small apps and services that are optimized for speed. The most important
application of the framework is to build REST APIs.
Why build a REST API in Lumen
To build a REST API with Lumen, signup to launch a server on Cloudways
. On Cloudways platform, you get Laravel in a 1-click install with an optimized
stack and pre-installed Composer.
Lumen is blazing fast.
It can handle more requests per second than Laravel.
It uses nikic/FastRoute instead of Symfony, thereby increasing
performance.
Laravel
hosting
How to Create a REST API with Laravel
Lumen
API LARAVEL
Updated on November 3, 2016 4 Min Read
Search
DEPLOY NOW!
Setup Laravel 5.7 Application in Just 1-click on Different Cloud Providers Like GCE , AWS , DO , Linode , Vultr
Features Pricing Enterprise Partnership Company Support Login START FREE
You might also like:
Note: If you want to use the Laravel Stack
Inside the Laravel public_html directory, run the following commands to create a Lumen
app inside the Laravel project :
> composer require "laravel/lumen" //installing Lumen > vendor/bin/lumen n
ew mylumen_car_app //creating Lumen app
From here you have 3 options to update the webroot:
Symlink your Lumen public directory to the Laravel public directory.
OR update the webroot using the Cloudways Application Settings page.
OR move Lumen’s index.php inside the Laravel public directory and
update the bootstapp/app.php path.
Next, inside the app’s public_html folder, run the following command to create a Lumen
project.
> composer create‐project laravel/lumen car_api
Change the webroot by adding /public (this is the public folder for all Laravel apps) in
the Cloudways Application Settings page so that the new webroot is now
public_html/public.
Load up the application URL in the browser and you will see the following page.
MySQL connection
I will use MySQL for this tutorial. Update the DB credentials in the .env file using the
MySQL ACCESS available on the Cloudways Application Page. The following fields
should be updated:
DB_DATABASE=<db_name> DB_USERNAME=<db_username> DB_PASSWORD=<db_password>
Next, uncomment the following lines in bootstrap/app.php
Quickly Host Laravel on DigitalOcean in Few Clicks
1. > composer require "laravel/lumen" //installing Lumen
2. > vendor/bin/lumen new mylumen_car_app //creating Lumen app
> composer require "laravel/lumen" //installing Lumen > vendor/bin/lumen new
mylumen_car_app //creating Lumen app
1. > composer create-project laravel/lumen car_api
> composer create-project laravel/lumen car_api
1. DB_DATABASE=<db_name>
2. DB_USERNAME=<db_username>
3. DB_PASSWORD=<db_password>
DB_DATABASE=<db_name> DB_USERNAME=<db_username> DB_PASSWORD=<db_password>
117
SHARES
$app‐>withFacades(); $app‐>withEloquent();
The Facade class is a static interface to classes available in the application’s service
containers. This class is required to access certain core components of Lumen. Eloquent
is the ORM that is used communicate with the MySQL database.
Migration
It is now time to create the database schema.
Create a table for Cars with four fields including the auto- increment id. The other three
fields are make, model, and year. To create the table, run:
> php artisan make:migration create_table_cars ‐‐create=cars
This will create a <date>_create_table_cars.php file inside the
database/migrations/ folder. I will now edit this file and define the table.
Add the following code inside up function:
Schema::create('cars', function (Blueprint $table) { $table‐>increments('id
'); $table‐>string('make'); $table‐>string('model'); $table‐>string('year')
; });
The up function will be triggered when the table is actually created during the migration.
The down function (no changes required in this function) will delete the table if the need
arises.
Now run the migration using:
> php artisan migrate Migration table created successfully. Migrated: 2016_
09_08_142212_create_table_cars
At this point, the table has been created and can be viewed in MySQL manager.
1. $app->withFacades();
2. $app->withEloquent();
$app->withFacades(); $app->withEloquent();
1. > php artisan make:migration create_table_cars --create=cars
> php artisan make:migration create_table_cars --create=cars
1. Schema::create('cars', function (Blueprint $table) {
2. $table->increments('id');
3. $table->string('make');
4. $table->string('model');
5. $table->string('year');
6. });
Schema::create('cars', function (Blueprint $table) { $table->increments('id'
$table->string('make'); $table->string('model'); $table->string('year');
});
1. > php artisan migrate
2. Migration table created successfully.
3. Migrated: 2016_09_08_142212_create_table_cars
> php artisan migrate Migration table created successfully. Migrated: 2016_0
9_08_142212_create_table_cars
The Model
Next step is the creation of the model. Create the app/Car.php file and add the
following code:
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Car exte
nds Model { protected $fillable = ['make', 'model', 'year']; } ?>
The Controller
Create a controller inside the app/Http/Controllers/CarController.php.
<?php namespace App\Http\Controllers; use App\Car; use App\Http\Controllers
\Controller; use Illuminate\Http\Request; class CarController extends Contr
oller{ public function createCar(Request $request){ $car = Car::create($req
uest‐>all()); return response()‐>json($car); } public function updateCar(Re
quest $request, $id){ $car = Car::find($id); $car‐>make = $request‐>input('
make'); $car‐>model = $request‐>input('model'); $car‐>year = $request‐>inpu
t('year'); $car‐>save(); return response()‐>json($car); } public function d
eleteCar($id){ $car = Car::find($id); $car‐>delete(); return response()‐>js
on('Removed successfully.'); } public function index(){ $cars = Car::all()
return response()‐>json($cars); } } ?>
1. <?php namespace App;
2.
3. use Illuminate\Database\Eloquent\Model;
4.
5. class Car extends Model
6. {
7. protected $fillable = ['make', 'model', 'year'];
8. }
9. ?>
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Car exten
ds Model { protected $fillable = ['make', 'model', 'year']; } ?>
1. <?php
2.
3. namespace App\Http\Controllers;
4.
5. use App\Car;
6. use App\Http\Controllers\Controller;
7. use Illuminate\Http\Request;
8.
9. class CarController extends Controller{
10.
11. public function createCar(Request $request){
12.
13. $car = Car::create($request->all());
14.
15. return response()->json($car);
16.
17. }
18.
19. public function updateCar(Request $request, $id){
20.
21. $car = Car::find($id);
22. $car->make = $request->input('make');
23. $car->model = $request->input('model');
24. $car->year = $request->input('year');
25. $car->save();
26.
27. return response()->json($car);
28. }
29.
30. public function deleteCar($id){
31. $car = Car::find($id);
32. $car->delete();
33.
34. return response()->json('Removed successfully.');
35. }
36.
37. public function index(){
38.
The routes
Now all that remains is the . I will write routes for creating, updating,
deleting and viewing cars.
Open up app/Http/routes.php and add the following routes.
$app‐>group(['prefix' => 'api/v1','namespace' => 'App\Http\Controllers'], f
unction($app) { $app‐>post('car','CarController@createCar'); $app‐>put('car
/{id}','CarController@updateCar'); $app‐>delete('car/{id}','CarController@d
eleteCar'); $app‐>get('car','CarController@index'); });
Notice that I have grouped the routes together into a common api/v1 route.
Testing It Out
Now, test it all out using curl.
Creation
> curl ‐i ‐X POST ‐H "Content‐Type:application/json" http://<unique‐to‐you>
.cloudwaysapps.com/api/v1/car ‐d '{"make":"toyota", "model":"camry", "year"
:"2016"}' {"make":"toyota","model":"camry","year":"2016","id":7}
After adding several more records, the DB would look like:
39. $cars = Car::all();
40.
41. return response()->json($cars);
42.
43. }
44. }
45. ?>
<?php namespace App\Http\Controllers; use App\Car; use App\Http\Controllers\
Controller; use Illuminate\Http\Request; class CarController extends Control
ler{ public function createCar(Request $request){ $car = Car::create($reques
t->all()); return response()->json($car); } public function updateCar(Reques
t $request, $id){ $car = Car::find($id); $car->make = $request->input('make'
$car->model = $request->input('model'); $car->year = $request->input('yea
r'); $car->save(); return response()->json($car); } public function deleteCa
r($id){ $car = Car::find($id); $car->delete(); return response()->json('Remo
ved successfully.'); } public function index(){ $cars = Car::all(); return r
esponse()->json($cars); } } ?>
addition of the routes
1. $app->group(['prefix' => 'api/v1','namespace' =>
'App\Http\Controllers'], function($app)
2. {
3. $app->post('car','CarController@createCar');
4.
5. $app->put('car/{id}','CarController@updateCar');
6.
7. $app->delete('car/{id}','CarController@deleteCar');
8.
9. $app->get('car','CarController@index');
10. });
$app->group(['prefix' => 'api/v1','namespace' => 'App\Http\Controllers'], fu
nction($app) { $app->post('car','CarController@createCar'); $app->put('car/{
id}','CarController@updateCar'); $app->delete('car/{id}','CarController@dele
teCar'); $app->get('car','CarController@index'); });
1. > curl -i -X POST -H "Content-Type:application/json" http://<unique-
to-you>.cloudwaysapps.com/api/v1/car -d '{"make":"toyota",
"model":"camry", "year":"2016"}'
2.
3. {"make":"toyota","model":"camry","year":"2016","id":7}
> curl -i -X POST -H "Content-Type:application/json" http://<unique-to-you>.
cloudwaysapps.com/api/v1/car -d '{"make":"toyota", "model":"camry", "year":"
2016"}' {"make":"toyota","model":"camry","year":"2016","id":7}
Updating
Next,I will update id = 1 to Toyota Supra 1999 (the previous valve was Toyota Camry
2016).
> curl ‐H "Content‐Type:application/json" ‐X PUT http://<unique‐to‐you>.clo
udwaysapps.com/api/v1/car/1 ‐d '{"make":"toyota", "model":"supra", "year":"
1999"}' {"id":1,"make":"toyota","model":"supra","year":"1999"}
Deletion
Now, I will delete id = 1.
> curl ‐X DELETE http://<unique‐to‐you>.cloudwaysapps.com/api/v1/car/1
“Removed successfully.”
View
This is what the final data should look like:
> curl http://<unique‐to‐you>.cloudwaysapps.com/api/v1/car [{"id":4,"make":
"chevrolet","model":"camaro","year":"1969"},{"id":5,"make":"dodge","model":
"intrepid","year":"2004"},{"id":6,"make":"acura","model":"integra","year":"
1999"}]
As a final confirmation,I can verify the data using the :
1. > curl -H "Content-Type:application/json" -X PUT http://<unique-to-
you>.cloudwaysapps.com/api/v1/car/1 -d '{"make":"toyota",
"model":"supra", "year":"1999"}'
2.
3. {"id":1,"make":"toyota","model":"supra","year":"1999"}
> curl -H "Content-Type:application/json" -X PUT http://<unique-to-you>.clou
dwaysapps.com/api/v1/car/1 -d '{"make":"toyota", "model":"supra", "year":"19
99"}' {"id":1,"make":"toyota","model":"supra","year":"1999"}
1. > curl -X DELETE http://<unique-to-
you>.cloudwaysapps.com/api/v1/car/1
> curl -X DELETE http://<unique-to-you>.cloudwaysapps.com/api/v1/car/1
1. > curl http://<unique-to-you>.cloudwaysapps.com/api/v1/car
2.
3. [{"id":4,"make":"chevrolet","model":"camaro","year":"1969"},
{"id":5,"make":"dodge","model":"intrepid","year":"2004"},
{"id":6,"make":"acura","model":"integra","year":"1999"}]
> curl http://<unique-to-you>.cloudwaysapps.com/api/v1/car [{"id":4,"make":"
chevrolet","model":"camaro","year":"1969"},{"id":5,"make":"dodge","model":"i
ntrepid","year":"2004"},{"id":6,"make":"acura","model":"integra","year":"199
9"}]
Cloudways MySQL manager
You might also like:
Conclusion
This article highlighted Lumen, a Laravel based micro framework that is optimized for
REST API. I created the model, controller and the view for the CURL based app. The aim
of this tutorial is to show how easy it is to create REST API with Lumen. If you have any
problems following the code or would like to contribute to the discussion, please leave a
comment below.
COMMENT NOW
Share your opinion in the comment section.
Create ToDo App With Authentication Using Lumen
Fahad Saleh
Fahad Saleh is a DevOps Engineer at Cloudways
Get Connected on:
Twitter Community Forum 
PRODUCT & SOLUTION
WordPress Hosting
Magento Hosting
PHP Cloud Hosting
Laravel Hosting
Drupal Hosting
Joomla Hosting
WooCommerce Hosting
Cloudways Platform
Cloudways API
Breeze – Free WordPress Cache
Add-ons
CloudwaysCDN
COMPANY
About us
Testimonials
Terms
Media Kit
Sitemap
SUPPORT
Knowledge base
Contact us
Blog
Community
Feedback
Free Website Migration
QUICK LINKS
Features
Pricing
Partners
Cloud Affiliate Program
PrestaShop Hosting CloudwaysBot
Follow Us On
   
52 Springvale, Pope Pius XII Street Mosta MST2653, Malta
© 2019 Cloudways Ltd. All rights reserved

Navigation menu