Build REST API using Laravel Lumen for your Application

Hello friends, today we will build REST API using Lumen a micro php framework by laravel. We already covered about the basics of REST Architecture in my previous post. So in this post we will not talk about the basics of REST API, and we will directly start building REST API. And after building REST API we will build the app in android platform.

So without wasting time lets build our REST API.

Build REST API using Lumen Video Tutorial

  • If you don’t want to read the post you can go to this video explanation as well.

  • If you are ok with written post then lets move ahead.

Tools Required

We will be using the following to Build our RESTful Web Services.

  • PHP Storm (Though you can use any other IDE but I will recommend using it).
  • Lumen by Laravel (The php framework)
  • XAMPP (For the dev environment)
  • POSTMAN (Rest client for testing the API)

I hope you got all the tools. Now lets discuss the database design.

Database Design

  • Here is my database design. I am going to build a very simple Question Answer Application. So keeping it very simple this is the database model I finalized.
build rest api database design
Database Design
  • This time you don’t need an SQL code for the database. Lumen will do it for you. Don’t get confused just keep reading 😉

Creating Lumen Project

  • Make sure you have composer installed in your computer.
  • Now go to the directory htdocs of xampp and open command window in the same directory. (you can use shift + right click to open command window in a specified folder).
  • Now run the following command.

  • In the above command MyQAApp is the name of your project. If you want you can change it to anything you like.
  • After running the command wait for sometime (it may take very long if you have a slow internet connection).

build rest api lumen project

  • After the above command finishes. You will find a folder with the project name created at htdocs.
  • Now go to web browser and try opening localhost/MyQAApp/public/ (make sure xampp is running and you are using the same project name).

build rest api lumen

  • You need to open this folder in PHP Storm as a project.

Lumen Directory Structure

  • Once you have opened the project in PHP Storm you will see the following directory structure.
build rest api php storm project
Directory Structure
  • You see many folders here but we need to care about only the following things.
    app: Here we will define models to perform database operations.
    app/http/controllers: Here we will define our app logics.  
    app/http/middlewares: We will define the API security here.
    database/migrations: We will define the database schema here.
    routes: Here we will define the endpoints for the API.

Setting Up Database

  • First create a database in phpmyadmin. You do not need to create any tables. Just create a database. (I have created a database named myqaapp).

build rest api creating database

  • Now come back to project in php storm and open .env file, and modify it as below.

  • I have changed the following, in the above file.
    DB_DATABASE=yourdatabasename
    DB_USERNAME=database username of xampp (root in this case)
    DB_PASSWORD= database password (nothing in this case)
    CACHE_DRIVER=array
  • Now we will create database schema in migrations.

Building Database Schema

  • On PHP Storm go to View->Tool Windows->Terminal. 

build rest api opening terminal

  • You will see the terminal window in the bottom.

Creating Migrations

  • On the terminal execute the following command.

  • In the above command users is the name of the table. You need to perform the above command for every table that we designed in our database. Make sure you create the migrations in the following sequence. The sequence is important as we are dealing with primary and foreign keys.

build rest api creating migrations

  • In these files we will design the database schema.

Designing Database Schema

Users Schema

  • Lets start with the first one users_table.php. You will see the following code inside.

  • Inside the method up() we will define the schema. We have already designed the database so we just need to add few lines inside the method up().
  • Modify the code as below.

  • The same way we will define the schema for others table as well. In the above code you can see we have written $table->string(’email’); this means the table has a new column name email with datatype string. You can check the official docs of laravel for the list of available datatypes.
  • The same way lets define schema for remaining 3 tables.

Categories Schema

Questions Schema

Answers Schema

  • So we have the database schema ready. Now lets do a migration to create the tables in MySQL as well.

Making Migration

  • In the terminal type php artisan migrate. And the database will be migrated automatically.

build rest api migrating database

  • Now check PhpMyAdmin and you will see the tables are created.

Making Models

  • Models will simplify the database. We will use the Laravel Eloquent ORM and Models and it will simplify the database operation like never before. You actually do not need to write a single line of SQL query if you are going to use it.
  • But the first thing is we need to enable the Eloquent, as it is not enabled by default.

Enabling Eloquent

  • Go to bootstrap/app.php. and uncomment the following lines.

build rest api enabling eloquent

  • Now for each database table we will create a model inside app folder. So we will create User.php, Categorie.php, Question.php and Answer.php.

User Model

  • Come inside the User.php and modify the model class as below. You can see below we are also defining the relationships.

Question Model

Category Model

Answer Model

  • So we have defined the models. Now lets build controllers.

Making Controllers

  • Now we will make the controllers. These controllers will perform the actual operations. All controllers file will be created inside app/http/controllers.

User Controller

  • Create a new php file named UserController.php. First we need to think what operation we need for a user. So for this app I have decided 3 operations.
    1. User Registration: A new user can register to the application.
    2. User Login: User can login to the application by providing username and password.
    3. Get My Questions: User can view all the questions that is asked by that user.
  • So Inside UserController.php we will define a class that will extend Controller, and inside the class we will define all the operation as separate functions.

Question Controller

  • For Question we will perform the following operations.
    1. Submit a new Question.
    2. Get all the questions.
    3. Get questions of an specified category.
  • So create a file named QuestionController.php and write the following code.

Category Controller

  • Create a new file named CategoryController.php and write the following code.

  • Finally lets create the AnswerController.

Answer Controller

  • Again create a new file named AnswerController.php and write the following code.

  • Our controllers are ready, now we will define URL routes to call the operations.

Creating URL EndPoints

  • Come inside routes/web.php. And write the following code.

Testing the API

  • Now lets test all the endpoints. For this I will be using POSTMAN you can use any REST Client.
  • So open postman. And write a URL. In my case the BASE URL is http://localhost/MyQAApp/public/ and we will add what we created after this.
  • So lets test createuser first, for this put the URL in POSTMAN, select request type as POST and add required parameters. (You can take help from the below screenshot).

 

build rest api postman testing
Create User
  • You can see it is working fine. The same way you need to test all the other routes as well.

Adding Basic Authentication

  • Now imagine we are using this API for our application. And someone gets the URL addresses of our API. Then what can happen? With the URL address our database can be flooded with spam values. So we need some authentication part so that we can accept only the request from the application.
  • There are many security models but here to keep it simple I will tell you about adding Basic Authentication.

Creating a MiddleWare

  • Come inside app/http/middleware and open the file Authenticate.php, remove everything and write the following code.

  • Now we will add this middleware to all routes. To do this come inside bootstrap/app.php. And add the following code inside Register Middleware section.

  • Now try sending the request in POSTMAN again. You will see the following output.

build rest api unauthorized

  • As you can see the error message that the request is an Unauthorized Request with status code 401. So our API is little secured now. As to send the request we need a username and password to authorize every request.

Sending Request with Basic Auth

  • Postman has an inbuilt option to set Basic Auth headers. Just click on Authorization and select Basic Auth.

build rest api basic auth

  • Now enter your API username and password that you have set, and send the request.

build rest api example

  • You can see now it is working fine.

Things I Left in this API

  • I left many things in this API as it is an example only to teach you the idea of building an API. I am mentioning some tasks that I left to make it simple. But if you want to learn you can try completing this API.
    1. No user update option.
    2. No pagination if there will be larger data it is not a good idea to fetch all at once.
    3. No upvote and likes on answers.
  • I pointed out some points, there may still be something that can be added. So comment below that what should be added on this API.

Build REST API using Laravel Lumen Source Code

  • If you are facing troubles you can get my source code from the below link.

So that all for this Build REST API Tutorial friends. I hope you got the idea of building RESTful Web Services.

In the next post we will build an Android Application using the new Kotlin Language for this API.

Meanwhile iff you are having any troubles or confusions, feel free to leave your comments. Also don’t forget to SHARE if you found this article helpful. Thank You 🙂

9 thoughts on “Build REST API using Laravel Lumen for your Application”

  1. Thanks for always making tutorials more simpler than ever.
    If I may ask, why did you implement relationships between the models in one way without implementing the corresponding inverse relationships between them.

    Thanks.

    Reply

Leave a Comment