How to build a simple REST API with Lumen

How to build a simple REST API with Lumen

In this Laravel 6 tutorial, we’ll learn how to build a simple REST API with Lumen. Lumen is a new project from Laravel creator Taylor Otwell. Lumen has the same foundation as Laravel and many of the same components. But Lumen is built for microservices, not so much for user-facing applications although it can be used for anything.

Introducing Lumen from Laravel

Lumen is a new project from Laravel creator Taylor Otwell. It's a "micro-framework", meaning it's a smaller, faster, leaner version of a full web application framework. PHP has two other popular micro-frameworks, Slim and Silex.

Lumen has the same foundation as Laravel, and many of the same components. But Lumen is built for microservices, not so much for user-facing applications although it can be used for anything.

Though this tutorial is about Lumen, a simple understanding of how Laravel works is all you need to follow along. You can check the git repository from here Rest api with lumen

RESTful APIs

First, we need to understand what exactly is considered a RESTful API. REST stands for REpresentational State Transfer and is an architectural style for network communication between applications, which relies on a stateless protocol (usually HTTP) for interaction.

HTTP Verbs Represent Actions

In RESTful APIs, we use the HTTP verbs as actions, and the endpoints are the resources acted upon. We’ll be using the HTTP verbs for their semantic meaning:

GET: retrieve resources
POST: create resources
PUT: update resources
DELETE: delete resources

Installing Lumen

Lumen utilizes Composer to manage its dependencies. So, before using Lumen, make sure you have Composer installed on your machine.

Via Lumen Installer

First, download the Lumen installer using Composer:

composer global require "laravel/lumen-installer"

Make sure to place the ~/.composer/vendor/bin directory in your PATH so the lumen executable can be located by your system.Once installed, the lumen new command will create a fresh Lumen installation in the directory you specify.

For instance, lumen new blog will create a directory named blog containing a fresh Lumen installation with all of Lumen's dependencies already installed. This method of installation is much faster than installing via Composer:

lumen new blog

Via Composer Create-Project

You may also install Lumen by issuing the Composer create-project command in your terminal:

composer create-project --prefer-dist laravel/lumen blog

Serving Your Application

To serve your project locally, you may use the Laravel Homestead virtual machine, Laravel Valet, or the built-in PHP development server:

php -S localhost:8000 -t public

If you run this command and visit http://localhost:8080, you will be able to see the following page.

Step 1: Configuration

.env file and replace the default **CACHE_DRIVER **and **QUEUE_DRIVER **values with the following:

CACHE_DRIVER=array
QUEUE_DRIVER=database

Step 2 : Database and Migrations

Let’s create our migration file. Run the following command:

php artisan make:migration create_products_table

This will create a new migration file for you in the database/migrations directory. Ourproduct resourcewill have the following attributes name, price and description.

Add the following code to the newly created migration file.

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateProductsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->integer('price');
            $table->longText('description');            
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('products');
    }
}

Edit **.env**with your database configurations and then run the following command to execute the migration.

php artisan migrate

Step 3: Create product model

You might already be used to creating models and controllers via artisan commands in Laravel, but unfortunately Lumen doesn’t support those commands. To see a list of available artisan commands in Lumen, run:

php artisan

Navigate to the app directory and create a new model called Product.php and paste those following code.

App/Product.php

namespace App;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $table = 'products';
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'price','description'
    ];

}

Unlike Laravel, Lumen does not initially load Eloquent and Facades. To be able to use them, we have to uncomment the following lines of code located in bootstrap/app.php

bootstrap/app.php

$app->withFacades();
$app->withEloquent();

$app->register(App\Providers\AppServiceProvider::class);
$app->register(App\Providers\AuthServiceProvider::class);
$app->register(App\Providers\EventServiceProvider::class);

Step 4: Setup controller

Let’s rename the ExampleController to ProductController. Navigate to the app\Http\Controller directory and paste those code to this ProductController.php file.

ProductController.php

namespace App\Http\Controllers;
use App\Product;
use Illuminate\Http\Request;

class ProductController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

     public function index()
     {

       $products = Product::all();
       return response()->json($products);
     }

     public function create(Request $request)
     {
       $product = new Product;
       $product->name= $request->name;
       $product->price = $request->price;
       $product->description= $request->description;

       $product->save();
       return response()->json($product);
     }

     public function show($id)
     {
        $product = Product::find($id);
        return response()->json($product);
     }

     public function update(Request $request, $id)
     { 
        $product= Product::find($id);

        $product->name = $request->input('name');
        $product->price = $request->input('price');
        $product->description = $request->input('description');
        $product->save();
        return response()->json($product);
     }

     public function destroy($id)
     {
        $product = Product::find($id);
        $product->delete();
        return response()->json('product removed successfully');
     }

}

Step 5 : Setup routes

It’s time to finally add our routes. Open up the web.php file in the routes folder and add the following code:


$router->group(['prefix'=>'api/v1'], function() use($router){

    $router->get('/items', '[email protected]');
    $router->post('/items', '[email protected]');
    $router->get('/items/{id}', '[email protected]');
    $router->put('/items/{id}', '[email protected]');
    $router->delete('/items/{id}', '[email protected]');

});

We define group our routes and add the prefix api/v1 since it’s a common parameter shared by all our URIs

Now insert some dummy data to products table like below. Then we will be able to test our application.

Step 6 : Testing our API

We’ll be making use of Postman to test our API. You can read more on getting started with Postman here.

GET Request with all items preview:

GET Request with single items preview:

POST Request for inserting new items preview:

PUT Request for updating items preview:

DELETE Request to delete items preview:

In this tutorial, we’ve learn how to build a simple REST API with Lumen. Hope this tutorial will help you. You can check the git repository from here <Rest api with lumen

What the difference between REST API and RESTful API?

What the difference between REST API and RESTful API?

Representational state transfer (REST) is a style of software architecture. As described in a dissertation by Roy Fielding, REST is an "architectural style" that basically exploits the existing technology and protocols of the Web. RESTful is typically used to refer to web services implementing such an architecture.

The short answer is that REST stands for Representational State Transfer. It’s an architectural pattern for creating web services. A RESTful service is one that implements that pattern.

The long answer starts with “sort of” and “it depends” and continues with more complete definitions.

Defining REST

Let’s start by defining what REST is and is not. For some, REST means a server that exchanges JSON documents with a client over HTTP. Not only is that not a complete definition, but it’s also not always true. The REST specification doesn’t require HTTP or JSON. (The spec doesn’t mention JSON or XML at all.)

The Origins of REST

Roy Fielding introduced the REST architectural pattern in a dissertation he wrote in 2000. The paper defines a means for clients and servers to exchange application data. A key feature is that the client doesn’t need to know anything about the application in advance. The link is to chapter five of his paper. While the entire dissertation describes the hows and whys of REST, that chapter defines the architectural pattern.

Fielding doesn’t mandate specific requirements. Instead, he defines REST regarding constraints and architectural elements.

REST’s Architectural Constraints

Here is a summary of the constraints.

  • Client-server – REST applications have a server that manages application data and state. The server communicates with a client that handles the user interactions. A clear separation of concerns divides the two components. This means you can update and improve them in independent tracks.
  • Stateless – servers don’t maintain any client state. Clients manage their application state. Their requests to servers contain all the information required to process them.
  • Cacheable – servers must mark their responses as cacheable or not. So, infrastructures and clients can cache them when possible to improve performance. They can dispose of non-cacheable Information, so no client uses stale data.
  • Uniform interface – this constraint is REST’s most well known feature or rule, depending on who you ask. Fielding says “The central feature that distinguishes the REST architectural style from other network-based styles is its emphasis on a uniform interface between components.” REST services provide data as resources, with a consistent namespace. We’ll cover this in detail below.
  • Layered system – components in the system cannot “see” beyond their layer. So, you can easily add load-balancers and proxies to improve security or performance.

A RESTful service is more than a web server that exchanges JSON, or any other, documents. These constraints work together to create a very specific type of application.

Applying the Constraints

First, the client-server, layered systems and stateless constraints combine to form an application with solid boundaries and clear separations between concerns. Data moves from the server to the client upon request. The client displays or manipulates it. If the state changes, the client sends it back to the server for storage. Fielding specifically contrasts REST with architectures that use distributed objects to hide data from other components. In REST, the client and server share knowledge about data and state. The architecture doesn’t conceal data, it only hides implementations.

The cacheable and uniform state constraints go one step further. Application data is available to clients in a clear and consistent interface and cached when possible.

So, that’s the technical definition of REST. What does it look like in the real world?

RPC Over HTTP vs. RESTful

Often when someone says that a service “isn’t REST,” they’re looking at the URIs or how the service uses HTTP verbs. They’re referring to REST’s presentation of data as a uniform set of resources.

This distinction is sometimes framed as a difference between remote procedures calls (RPC) and REST. Imagine a web service for listing, adding, and removing, items from an e-commerce inventory.

In one version, there’s a single URL that we query with HTTP GETs or POSTs.  You interact with the service by POSTing a document, setting the contents to reflect what you want to do.

Add new items with a POST with a NewItem:

POST /inventory HTTP/1.1
 
{
    "NewItem": {
          "name": "new item",
          "price": "9.99",
          "id": "1001"
      }
}    

Query for items with a POST and an ItemRequest:

POST /inventory HTTP/1.1
 
{
    "ItemRequest": {
          "id": "1001"
      }
}

Some implementations accept a request for a new item with a get, too.

POST /inventory?id=1001 HTTP/1.1

We also change or delete items with a POST and an ItemDelete or ItemUpdate.

POST /inventory HTTP/1.1
 
{
    "ItemDelete": {
          "id": "1001"
      }
}

This isn’t REST. We’re not exchanging the state of resources. We’re calling a function with arguments that happen to be in a JSON document or URL arguments.

A RESTful service has a URI for each item in the inventory.

So, adding a new item would look like the example above.

POST /item HTTP/1.1
 
{
    "Item": {
          "name": "new item",
          "price": "9.99",
          "id": "1001"
      }
}    

But the similarities end there. Retrieving an item is always a GET:

GET /item/1001 HTTP/1.1   

Deleting is a DELETE:

DELETE /item/1001 HTTP/1.1  

Modifying an item is a PUT:

POST /inventory HTTP/1.1
 
{
    "Item": {
          "name": "new item",
          "price": "7.99",
          "id": "1001"
      }
}    

The difference is important. In REST, operations that use distinct HTTP actions. These verbs correspond directly to the activity on the data. GET, POST, PUT, DELETE and PATCH all have specific contracts. Most well-designed REST APIs also return specific HTTP codes, depending on the result of the request.

The critical point is that the URIs operate on the data, not on remote methods.

But there’s another reason why the resource model is essential.

REST vs RESTful and the Richardson Maturity Model

When you model your URIs after resources and use HTTP verbs you make your API predictable. Once developers know how you defined your resources, they can almost predict what the API looks like. Here again, the emphasis is on understanding the data, not the operations.

But even if you can’t make the API entirely predictable, you can document any REST service with hypertext. So, each item returned in the inventory app would contain links for deleting, modifying, or setting the inventory level of the resource. Fielding says that before a service is RESTful, it must provide hypertext media as part of the API.

Many sites don’t meet this requirement but are still called REST. Fact is, many sites break the rules in one way or another. So many that Leonard Richardson created a model breaks down REST into levels of compliance

We’ve already covered the source levels:

  • 0 – exporting an API over HTTP with methods called with arguments
  • 1 – Exporting resources instead of methods
  • 2 – Proper use of HTTP verbs
  • 3 – Exporting hypertext with objects that make all or part of the API discoverable.

Richardson’s model is his own, and it doesn’t map directly into Fielding’s spec. Since Fielding requires level three, he would say that most apps aren’t REST anyway.

The point is many services that we colloquially refer to as REST, technically aren’t.

REST vs RESTful: Does It Matter?

So, does the REST vs. RESTful comparison matter? Probably not. How well your architecture complies with an arbitrary standard isn’t as important with how well it suits your needs and can grow with your business.

The REST architectural pattern has many advantages. Fielding designed it for the web and, 18 years later, most of the constraints he had in mind are still with us. In 2000 we didn’t have Android or the iPhone. IE5 had 50% of the browser market share. It’s biggest rival was Firefox. But Fielding recognized what online applications needed and how web clients would evolve from HTML display engines into complete applications. The tools we use today have grown to suit REST, not the other way around.

Thank you for reading. Hope this tutorial will help you!

What is REST API? | Restful Web Service

What is REST API? | Restful Web Service

In this post "Restful Web Service", you'll learn: What is Web services, what is API, What is REST API, How REST works and Implementation of REST API

What is REST API? | Restful Web Service

A REST API defines a set of functions to process requests and responses via HTTP protocol.

REST is used in mobile application as well as in web applications.


Top Laravel Development Companies Reviews

Top Laravel Development Companies Reviews

Among the list of Best Laravel development companies, TopDevelopers has chosen the most acclaimed laravel developers for the visitors so as to make them avail the extremely wonderful service ever offered. The web development companies listed here...

Among the list of Best Laravel development companies, TopDevelopers has chosen the most acclaimed laravel developers for the visitors so as to make them avail the extremely wonderful service ever offered. The web development companies listed here have passed the stringent assessments carried out by TopDevelopers in order to get approved as top Laravel service providers. Get in touch with the most sought-after Laravel developers in the market for your assistance.

Here is the List of Best Laravel Development Companies.