We are the part of the holding

How to Build a RESTful API in PHP (with Laravel)

  • 7-8 min read
  • September 24, 2021
  • 👍 Rating — 4.9 (15 votes)

PHP has long been one of the most popular programming languages ​​, as it makes it easy to maintain and build a rich web application. Most of the interactive and dynamic websites we see today need a set of tools to create and consume APIs.

Today, a useful API helps in content development and improves user experience and helps achieve business goals. This language is used by many developers and the software that has recently been the most successful in deploying web applications.

If you’ve ever experienced software development before, you will probably be familiar with RESTful APIs and how useful they can be. For more details, we suggest that you familiarize yourself with our article.

Let’s overview of the process of building a PHP RESTful API with Laravel.

Requirements

Here are technologies that we use to build API:

  • PHP. We have chosen PHP as the programming language for API development. There are several ways to work with PHP, but we’ll use Docker to run our services.
  • Composer. It is an application-level package manager for the PHP programming language that allows you to declare the libraries your project depends on and manage (install/update) them for you.
  • Laravel
  • Docker

Let’s download and install Composer. 

Install

Since the Composer installation is completed, we can install Laravel by running the first one command:

composer create-project laravel/laravel your-project-name 4.2.0

After this command, the Composer should download and install Laravel and the necessary dependencies, creating a project with which we will work in the future. You can read more about the installation here.

Once downloading and installing are finished, you can test the installation using the following command:

php artisan serve --port=8080

Docker

Docker is used to running services in a containerized environment. It takes over the functions of installing the necessary software so that you can focus on coding. The Docker container is useful for running APIs and testing locally on your machine. You can find out how to install Docker on your computer here.

Docker containers are present throughout the software development cycle, and their primary use is in deployment.

Since the Docker installation is complete, you can start building the PHP service.

The first place to start is creating a “Dockerfile.” Our actions will be as follows:
step #1  is to point which the docker container to build from

FROM php:7.0.28-apache

step #2 To install all the system dependencies and enable PHP modules

RUN apt-get update && apt-get install -y
 libicu-dev
 libpq-dev
 libpng-dev
 libmcrypt-dev
 mysql-client
 git
 zip
 unzip
 && rm -r /var/lib/apt/lists/*
 && docker-php-ext-configure pdo_mysql --with-pdo-mysql=mysqlnd
 && docker-php-ext-install
 intl
 mbstring
 mcrypt
 pcntl
 pdo_mysql
 pdo_pgsql
 pgsql
 zip
 gd
 opcache

step #3 To install composer

RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/bin/ --filename=composer

step #4 To set our application folder as an environment variable

ENV APP_HOME /var/www/html

step #5 Change uid and gid of apache to docker user uid/gid

RUN usermod -u 1000 www-data && groupmod -g 1000 www-data

step #6 Enable apache module rewrite

RUN a2enmod rewrite
RUN a2enmod ssl
RUN a2enmod headers

step #7 Set up apache configs and document root

ENV APACHE_DOCUMENT_ROOT=/var/www/html/public
RUN sed -ri -e 's!/var/www/html!${APACHE_DOCUMENT_ROOT}!g' /etc/apache2/sites-available/*.conf
RUN sed -ri -e 's!/var/www/!${APACHE_DOCUMENT_ROOT}!g' /etc/apache2/apache2.conf /etc/apache2/conf-available/*.conf

step #8 Define the command: mod_rewrite for URL rewrite and mod_headers for .htaccess extra headers like Access-Control-Allow-Origin-

RUN a2enmod rewrite headers

step #9 Now we need to copy source files and run composer

COPY . $APP_HOME

step #10 Install all PHP dependencies

RUN composer install --no-interaction

step #11 Change ownership of our applications

RUN chown -R www-data:www-data $APP_HOME

We can configure our application services in a docker-compose.yml file and define the API and a database.

version: "3"
services:

  laravel:
    build: .
    ports:
      - "8080:80"
    env_file:
      - .env
    volumes:
      - .:/var/www/html:cached
    depends_on:
      - laravel-db

  laravel-db:
    image: mysql:5.6
    ports:
      - "3306:3306"
    env_file:
      - .env
    volumes:
      - laravel-db:/var/lib/mysql

volumes:
  laravel-db:

The docker-compose.yml file provides two services.

  • laravel – This will define our PHP Laravel service. It will contain a volume of our code, and ports to access an API through the browser.
  • laravel-db – This will define the MySQL service to store our data.

It references a .env file, which is used as an environment. Now we are going to create a .env file to store our environment variables.

WEBROOT=/var/www
WEBROOT_PUBLIC=/var/www/public

COMPOSER_DIRECTORY=/var/www
COMPOSER_UPDATE_ON_BUILD=0

LARAVEL_APP=0
RUN_LARAVEL_SCHEDULER=0
RUN_LARAVEL_MIGRATIONS_ON_BUILD=0
PRODUCTION=0
PHP_VERSION=7.2
ALPINE_VERSION=3.7

COMPOSER_HASH=544e09ee996cdf60ece3804abc52599c22b1f40f4323403c44d44fdfdd586475ca9813a858088ffbc1f233e9b180f061

NGINX_HTTP_PORT=80
NGINX_HTTPS_PORT=443
PHP_MEMORY_LIMIT=128M
PHP_POST_MAX_SIZE=50M
PHP_UPLOAD_MAX_FILESIZE=10M

MYSQL_HOST=laravel-db
MYSQL_ROOT_USER=root
MYSQL_ROOT_PASSWORD=laravel
MYSQL_DATABASE=laravel
MYSQL_USER=laravel
MYSQL_PASSWORD=laravel
MYSQL_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=laravel
DB_PASSWORD=laravel
DB_HOST=laravel-db

Docker Compose

Now it is possible to call the services locally for viewing API. Here are some docker-compose commands.

docker-compose up

If we made everything right, there would be possible to go to https://localhost:8080, where the Laravel home page will be shown.

Planning the API

We want to create feature-rich APIs to make our services demand.
Let’s take an example with the URL https://www.photoalbum.com, but you can name your domain whatever you want.
Our first step will be to define photo API:

GET https://www.photoalbum.com/photo/1 – to get the photo with an id 1
POST https://www.photoalbum.com/photo – to create the photo
PUT https://www.photoalbum.com/photo/1 – to update the photo with an id 1
DELETE https://www.photoalbum.com/photo/1 – to delete it

Every picture should have:

  • id
  • URL
  • name
  • created date
  • updated date

Laravel usage will allow us to define a resource controller.

A tool like Docker allows you to isolate a specific environment. And now, through the docker container, using Laravel commands, let’s create API functions:

docker-compose run --rm laravel /bin/bash

Then create a photos table with the command

php artisan migrate:make create_photos_table

With the second command, we made a database migration called Photos
Check the app / database / migrations section. During the migration, the PHP code will also run, and the database table will be created. Thus, our photos will be stored in the database and, if necessary, transferred to Laravel.

Now we need to add a photo URL and name to the migration.

<?php use IlluminateDatabaseSchemaBlueprint; use IlluminateDatabaseMigrationsMigration; class CreatePhotosTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('photos', function($table) { $table->increments('id');
      $table->string('url')->unique();
      $table->string('name');
      $table->timestamps();
    });
  }

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

}

To start the migration we will use the next command.

php artisan migrate

Laravel Controller

Let’s create a Laravel Controller to define all endpoints.

php artisan controller:make PhotoController

After this we have to add our routes to the app/routes.php file:

Route::resource('photo', 'PhotoController');

It’s time to define our PhotoController:

class Photo extends Eloquent {

/**
 * The database table used by the model.
 *
 * @var string
 */
 protected $table = 'photos';

/**
 * The attributes excluded from the model's JSON form.
 *
 * @var array
 */
 protected $hidden = array('');
 }

Make sure you add these techniques methods to the PhotoController class.

Getting a list of Photos

In the beginning, we need to define the index by doing this we get a list of photos.

/**
   * Display all photos.
   *
   * @return Response
   */
  public function index()
  {
    $photos = Photo::all();
    return $photos;
  }

Creating a photo

This will store our photo in the database and return in JSON our newly created id and photo record. We get user input by calling the Input::get method.

/**
   * Store a newly created photo.
   *
   * @return Response
   */
  public function store()
  {
    $photo = new Photo;
    $photo->url = Input::get('url');;
    $photo->name = Input::get('name');;
    $photo->save();
    return $photo;
  }

Updating a photo

Using the ID, we can find the photo in the database. Next, if necessary, change the URL and name entered by the user, and the record will be saved and returned to the user as a JSON object.

/**
   * Update the photo.
   *
   * @param  int  $id
   * @return Response
   */
  public function update($id)
  {
    $photo = Photo::find($id);
    $photo->url = Input::get('url');;
    $photo->name = Input::get('name');;
    $photo->save();
    return $photo;
  }

Deleting a photo

Using the ID also we can remove a photo from the database.

/**
   * Remove the photo
   *
   * @param  int  $id
   * @return Response
   */
  public function destroy($id)
  {
    $photo = Photo::find($id);
    $photo->delete();
  }

Conclusion

In this article, we learned how to install Composer, Laravel, Docker, and use containers to build our Laravel API. To create a Laravel application and databases, we used Docker Compose, which gives us the ability to store data in the database. And also, the Photo Controller was created, which allows you to create APIs in Laravel.

Use the Laravel Passport, it has a mechanism to generate access tokens to work with API https://laravel.com/docs/7.x/passport
You should use Laravel Resources: https://laravel.com/docs/7.x/eloquent-resources
Laravel supports ::paginate - method for all the records so you can simple output Photo::paginate(20) to get paginated list

Creator

Expert & Evangelist in business optimization tools like fintech, logistics, on-demand services apps who will help you to understand the core ideas of the outlined themes by my articles.
Leave a comment

How can we help you?

  • Indicating scope, timeframes, or business challenges would allow us to provide a better response
  • Our expert team will get back to you within 24h for free consultation
  • All information provided is kept confidential and under NDA

Looking forward to your message!

spinner