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

PHP has been the most popular web language in the present times by being simple to maintain, and quick to create feature-rich web applications. Websites that are dynamic, interactive, secure and efficient, need a powerful tool set to create and consume APIs.

An efficient API is needed in our times in order to develop content that boosts discoverability and help achieve business goals, PHP is the language that most web developers use and software that has recently been the most successful on deploying web applications.

If you are using PHP you probably already know how useful RESTful APIs can be. You can brush up on API concepts.

Now let’s look at building a PHP RESTful API with Laravel.

Requirements

Let’s look at these technologies as we build our API:

  • PHP
  • Composer
  • Laravel
  • Docker

PHP will be our language of choice in developing our API. There are many ways we can install PHP on our system, although we will be using Docker to run our services.

Composer is a package manager for PHP. You can declare the dependencies your application depends on and it will download them for you to use. Let’s download and install Composer.

Install

Follow this link to download:

https://getcomposer.org/download/

Follow this link to Install:

https://getcomposer.org/doc/00-intro.md

Now we can install Laravel by running the Composer command:

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

By running this command Composer will download and install Laravel and any needed dependencies, creating a project for us to start working. You can read the full installation quick start here:

https://laravel.com/docs/4.2/quick

Once everything has been downloaded you can test out the installation by running:

php artisan serve --port=8080

Docker

Docker is very useful for running our services in a containerized environment. It will install all the needed software so we can focus on coding. A Docker container will provide a place for us to run our API and test locally on our computer. For instructions on how to install Docker for mac follow this link:

https://docs.docker.com/docker-for-mac/install/

There are also ways to install for Windows and Linux.

Once Docker has been installed we can begin to create our PHP service.

We will begin by creating a “Dockerfile”. This will define what we want to create a PHP service, install Composer and create our Laravel project.

# Use this docker container to build from
FROM php:7.0.28-apache

# 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

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

# set our application folder as an environment variable
ENV APP_HOME /var/www/html

# change uid and gid of apache to docker user uid/gid
RUN usermod -u 1000 www-data && groupmod -g 1000 www-data

# enable apache module rewrite
RUN a2enmod rewrite
RUN a2enmod ssl
RUN a2enmod headers

# apache configs + 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

# mod_rewrite for URL rewrite and mod_headers for .htaccess extra headers like Access-Control-Allow-Origin-
RUN a2enmod rewrite headers

# copy source files and run composer
COPY . $APP_HOME

# install all PHP dependencies
RUN composer install --no-interaction

# change ownership of our applications
RUN chown -R www-data:www-data $APP_HOME

Now that we have our Dockerfile, we can define our docker-compose.yml file. This will define our Laravel API and a MySQL database we can easily use to store data.

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:

This docker-compose.yml file creates two services for us.

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

This also references a .env file, which is an environment file.

Let’s 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 we can bring up our services locally to view our Laravel API. Let’s start with some docker-compose commands.

docker-compose up

If there were no errors you should be able to go to http://localhost:8080 and see the Laravel home screen.

laravel home

Planning the API

We will plan our service to use best practices so we can maintain and build feature-rich APIs. The URL https://www.ourphotos.com is just an example. You will likely change this to your own domain.

First, let’s define our photo API:

  • GET
    • https://www.ourphotos.com/photo/1 – This will get the photo with an id of 1
  • POST
    • https://www.ourphotos.com/photo – This will create the photo
  • PUT
    • https://www.ourphotos.com/photo/1 – This will update the photo with an id of 1
  • DELETE
    • https://www.ourphotos.com/photo/1 – This will delete the photo with an id of 1

Each photo will contain:

  • id of the photo
  • URL
  • name
  • created date
  • updated date

With Laravel, we can define a resource controller, that will make it easy for us to create this API.

Docker is very useful to be able to isolate a certain environment. Let’s login to the docker container and run Laravel commands, that will create features of our API:

# This will log us into the docker container which will enable us to run Laravel commands
docker-compose run --rm laravel /bin/bash

# This will create a photos table for us
php artisan migrate:make create_photos_table

The first docker-compose run command will log us into the container so we can run Laravel commands.

The second command will create a database migrate for us called Photos. Under app/database/migrations you can see your newly created migration. A migration will run PHP code and create a MySQL table. By doing this we can store our photos in our database and have them served up in Laravel.

Let’s add to our migration so we can store a photo URL and name:

<?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');
  }

}

Now we can run this command to run the migration:

php artisan migrate

Laravel Controller

Now we have our database running we can create a Laravel Controller that will define all our endpoints.

First, we need to create the controller:

php artisan controller:make PhotoController

Now we need to add our routes to the app/routes.php file:

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

Finally, we can define our PhotoController:

<?php

class PhotoController extends BaseController {
  // We will define our API endpoints here.
}

And we also need to create a file models/Photo.php

<?php
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('');
}

Let’s add these methods to our PhotoController class.

Getting a list of Photos

The first endpoint we will define is our index. By calling this we can 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

This will find the photo record in the database from the id. Then we can update from the user input of URL and name. It will then save the record in the database and return the JSON object back to the client.

 /**
   * 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

This will remove the photo from the database by calling the endpoint with the photo id.

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

By using a Laravel resource controller we can easily and powerful set up a RESTful API.

Testing the Laravel API

Laravel will give us a powerfully simple API that we can consume. If you have your Docker container running we can test out the API.

Let’s use Postman to test our API calls:

Once you have deployed your application you can start using RapidAPI.

Click here to add your API and get started with RapidAPI.

Conclusion

In this article, we learned how to install Composer, Laravel, Docker, and how we can leverage containers to create our Laravel API.

We used Docker Compose to create a Laravel application and MySQL service, we can now save our data to a database and have it persist.

We created Photo Controller that lets us build powerful yet simple APIs in Laravel.

Finally, we tested out our API with Postman to see how the data structure can be consumed.

Related Resources

 

The post How to Build a RESTful API in PHP (with Laravel) appeared first on Last Call – RapidAPI Blog.

Source: RapidAPI