Build a Simple RESTful API in PHP

Build a Simple RESTful API in PHP

This post will teach you how to create a simple RESTful API in PHP

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.

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: download/

Follow this link to Install: download

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:

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:

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 https://localhost:8080 and see the Laravel home screen.

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.

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:

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. Thank you for reading !

Integrate PHP Laravel 5.8 APIs in Angular 7

Integrate PHP Laravel 5.8 APIs in Angular 7

For PHP Laravel APIs to integrate in Angular 7, we have to write APIs in api.php file in Laravel which is in the routes folder in Laravel project structure. For the sake of this article, we are using example of User API.

we commonly use PHP Laravel 5 for database integration and Angular for frontend single page applications. So it makes sense to write about integrating PHP Laravel APIs with Angular frontend.

1. Develop Laravel API

Lets setup the database first. We follow proper Laravel structure through commands and code.

1.1 Create Laravel API migration

For PHP Laravel APIs to integrate in Angular 7, we have to write APIs in api.php file in Laravel which is in the routes folder in Laravel project structure. For the sake of this article, we are using example of User API. For User API to fetch and save data, you have to first setup database table. For that you have to write the migration for the table the command to create migration is written below.

php artisan make:migration create_user_table

After creating a migration, you have to make a model for the table that you have created. Which can be made by command written below.

1.2 Laravel model command

php artisan make:model User

short hand for creating migration and model both you will use this command

php artisan make:model User -m

After using this command the migration and model is made.

1.3 Laravel migration code example

Now you can write table in the migration. Below is the example to write table in migration.

public function up()
 {
 Schema::create('users', function (Blueprint $table) {
 $table-&gt;increments('id');
 $table-&gt;string('email')-&gt;unique();
 $table-&gt;string('first_name');
 $table-&gt;string('last_name');
 $table-&gt;string('password');
 $table-&gt;enum('account_status',['active','pending','rejected'])-&gt;default('pending');
 $table-&gt;enum('gender',['male','female']);
 $table-&gt;timestamps();
 });
 }

You can see the more about how to write table in the migration go to this link:

https://laravel.com/docs/5.7/migrations. After writing the table you have to run this command to migrate the table into the database

php artisan migrate

After migration, you have to write a method into the model that was created to get, update, or add data into the table. For an API to run you have to make,

Route::post('allUsers','[email protected]');

1. 4 Laravel controller command

php artisan make:controller UserController

1.4 Laravel controller code example

The controller function will look like this.

public function getAllUsers(){
 $count = User::All()-&gt;count();
 if($count &gt; 0){
 $users = User::role(['user','admin','dealer'])-&gt;get();
 return response()-&gt;json($users);
 }else{
 return response()-&gt;json("Users Not Found");
 }
 }

You can also make resource and collection to return the response. You can go this link and check the eloquent resources and collection https://laravel.com/docs/5.7/eloquent-resources.

So in this api the api is using UserController Method getllAllUsers to get the users from the database. After that you have to serve the laravel project to use these apis into angular project.

2. Integrate Laravel API in Angular

First setup your angular project using this command. Using Angular Cli.

ng new project_name

After that make your first component. For making component use this command.

ng generate component Users
// Or short hand:
ng g c Users

Four files will be generated after running that command. After that design your page in the html file

and in the ts file your code goes there. After that you have to make service to integrate the api calls that has been written in the Laravel so to create a service run this command.

ng generate service User
// Or short hand:
ng g s User

After running this command 2 file will be generated you will write the code in the ts file name users.service.ts there you will first import the HttpClient first. Then go to the environment folder and write the the api served url of the laravel project for local the url will look like this.

http://127.0.0.1:8000

The Laravel project will always serve on the 8000 port.

After importing the HttpClient then import the environment.ts file in the users service and get the api url from there. For importing just import the HttpClient into the constructor of the service.ts file.

After importing our service constructor will look like this.

 apiUrl: any;
constructor(private http: HttpClinet){
this.apiUrl = environment.apiUrl;
}

After that write a function to to call the API of the Laravel and we will use the HttpClient in the function an example is written below.

getAllUsers() {
 return this.http.get(this.apiUrl + 'allUsers/')
 .pipe(map((response: any) =&gt; {
 return response.json();
 }));
 }

This function is returning the data of all the users and parse then into the JSON response and return from where this function will get called.

After creating this function to get the data from the Laravel API now we will use this function into the the component that we have created first. To use the users service function import the users.service.ts file into the constructor of the users component. So this is the example to use the this service into the component.

The constructor will look like this after importing

constructor(private usersService: UsersService){
}

Here you can change the variable name for the user Service. You can set the variable name as you like. There is an ngOnInit() function in every component this is the first function to get called when ever the project gets served or this component is called. To get all the users from the service function that is calling Laravel API call to get all users the code will look like this.

allusers: any;
getUsers(){
this.usersService. getAllUsers()
.subscribe({
response =&gt; {
this.allusers=response;
},
 });
}

Here we have made first a global variable that is storing the response from the call into itself so that the response can be used the users.component.html file and anywhere in the users.component.ts file.

The getUsers function is calling the service function gellAllUsers to get the user and save it into the local variable. Now you can use this variable in whatever the way you like into your html page to show it on the webpage.

In Angular, you can also make the model to map the response also so for that you need to make a file names users.model.ts there is no specific command for that. So the model is made for the easiness to use the response of the API. Example is given below.

export class User{
 id: number;
 first_name: string;
 last_name: string;
 email: string;
 gender: string;
 status: string;
}

For mapping the response on to the model we will use Observables. Observable provide the support for passing the messages between creators of the observables and the subscribers in our application. Here the subscriber will be our getUsers function in the users.component.ts file and the Observable will be defined in the users.service.ts.

For using observers we will import the rxjs Observable into the users.service.ts file. Then after that the Observable will be used like this as shown in example below.

getUsers(): Observable&lt;{data: Users[]}&gt;{
 const headers = new HttpHeaders({'Content-Type': 'application/json'});
 return this.http.get&lt;{status_code: number, data: Users[], message: string}&gt;(this.apiUrl +
'allUsers', {headers: headers});
 }

Here the observable is parsing the response into the user model which we have created above as we are getting all the users from the API response so we are use Users[] array. And to get its parsed over here you have to format the response also in the Laravel API function. After this we also need to change the users.component.ts file so it will look like this.

 

allusers: Users[];

First we need to make your allUsers variable type to Users[] as the model and as we have done it in the service file the the gellUsers function will able to map response now.

getUsers(){
this.usersService. getAllUsers()
.subscribe({
response =&gt; {
this.allusers=response;
},
 });
}

Now it has made it easy for you to get the variable easily that are in the users model if you want to see the firstname of all the users you can easily do this

this.allusers.foreach(element =&gt;{
console.log('First Name',element.firstname);
})

as firstname is the variable that is in the model of Users.

If you follow this detailed tutorial, you can learn to write the APIs in Laravel and to integrate them in Angular project.

Thanks for reading. If you liked this post, share it with all of your programming buddies!

This post was originally published here

Tutorial Laravel 6 with Docker and Docker-Compose

Tutorial Laravel 6 with Docker and Docker-Compose

In this tutorial, we'll learn how we can use Docker and Compose to develop and run Laravel 6 applications locally.

Following this tutorial you'll learn:

Docker is a container tool that allows developers and organizations to build, run and deploy applications using containers.

Containers are standalone images that allow developers to package applications with their dependencies. They share the kernel and resources of the system where they are running and they provide isolated environments for applications.

Docker makes use of <a href="https://morioh.com/p/544a7cbf0be5" target="_blank">Dockerfile</a> files to define and describe the parts and dependencies used by an application and also commands to run in order to install the dependences and start the application.

Installing Docker

start by installing Docker for your type of operating system by following one of these official guides:

Docker-Compose

The official documentation describes docker-compose as:

A tool for defining and running multi-container Docker applications. With Compose, you use a YAML file to configure your application’s services. Then, with a single command, you create and start all the services from your configuration. To learn more about all the features of Compose, see the list of features.
Using docker-compose involves three easy steps:

  1. First, you need to define/describe your app environment with a ```Dockerfile``` so you can reproduce it anywhere.
    
  2. Second, you need to create ```docker-compose.yml``` file and define the services required for running your application so you can run them in multi containers.
    
  3. Finally you just need to run ```docker-compose up``` and Compose will start all the services for your application
    
Creating a Laravel 6 Project

Let's create a Laravel 6 project and then see how we can dockerize it using Docker.

We have different ways to create Laravel projects: Using Composer (PHP package manager), cloning from GitHub or downloading using cURL.

Using Composer

If you have Composer installed on your system then you can simply use the following command to create a Laravel project:

composer create-project --prefer-dist laravel/laravel laravelproject

Using GitHub Repository

Alternatively if you don't want to install Composer in your system, you can also clone Laravel from GitHub using:

git clone https://github.com/laravel/laravel.git laravelproject

Installing the Project Dependencies

Now, let's install the project's dependencies. If you have Composer installed, simply run the following command from within your project's root folder:

composer install 

If you don't have Composer installed on your system. You can also use Docker with the official composer image to install dependencies by running the following command from the project's root folder:

docker run --rm -v $(pwd):/app composer/composer install

The --rm switch tells Docker to automatically clean up and remove the container after doing the task and exiting.

This is what the docs says about that:

By default a container’s file system persists even after the container exits. This makes debugging a lot easier (since you can inspect the final state) and you retain all your data by default. But if you are running short-term foreground processes, these container file systems can really pile up. If instead you’d like Docker to automatically clean up the container and remove the file system when the container exits, you can add the <em>--rm</em> flag:
The command: -v $(pwd):/app instructs Docker to mount the current directory on the host system retrieved using $(pwd) to /app in the container . What app? Simply because the composer tool in the container will look for a composer.json file in this folder.

After finishing the installation, either way, you'll find a vendor folder with all dependencies inside your Laravel project.

Creating a Dockerfile

Now, after installing Docker and Docker-compose and creating the laravel project let's create a Dockerfile to define our environmenet. Create a new Dockerfile file in the application directory and start by adding the first command:

FROM php:7.2.2-fpm

This tells Docker to download and use the php:7.2.2-fpm image.

Next add:

RUN apt-get update -y && apt-get install -y libmcrypt-dev openssl
RUN docker-php-ext-install pdo mcrypt mbstring

This run apt-get to install the dependencies and extensions required by Laravel.

If you want to install Composer you can also add this command:

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

Now, add:

WORKDIR /app
COPY . /app

This tells Docker to set the working directory in the container to /app and copy the files (Laravel project) in our current folder (in our system host) to the /app folder in the container.

If you didn't install the dependencies using the previous methods you can install them using:

RUN composer install

Now, let's run the artisan serve command using the CMD command:

CMD php artisan serve --host=0.0.0.0 --port=8000

This will serve the Laravel project from the port 8000.

Finally, you need to expose the port 8000 from the container using:

EXPOSE 8000

This is the complete Dockerfile:

FROM php:7.2.2-fpm
RUN apt-get update -y && apt-get install -y libmcrypt-dev openssl
RUN docker-php-ext-install pdo mcrypt mbstring
RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
RUN docker-php-ext-install pdo mcrypt mbstring
WORKDIR /app
COPY . /app
RUN composer install

CMD php artisan serve --host=0.0.0.0 --port=8000
EXPOSE 8000

Building the Docker Image

After creating the Dockerfile, you are ready to create the actual Docker image. From your terminal, navigate to the root folder of your project and run:

docker build -t my-laravel-image .

Using the -t switch we can specify the tag/name of the Docker image. For the dot means the current folder will be used as the context for the image to be built. Remember the COPY command in the Dockerfile? its source folder is this folder so we can copy the files from our project to the container file-system.

Running the Docker Image Using Docker

After building the Docker image (my-laravel-image) you can now run it using:

docker run -p 8000:8000 my-laravel-image

You can now access your application from your browser at <a href="http://localhost:8000/" target="_blank">http://localhost:8000</a>.

Running the Docker Image Using Docker-compose

Docker-compose is more useful to build multi containers for the same application but it can also used to run a single Docker image. So first, create a docker-compose.yml file in the root folder of your project and add the following content:

web:
    image: my-laravel-image
    ports:
        - 8000:8000
    volumes:
        - ./:/app

We are defining a volume using ./:/var/www which simply mount our current directory ./ in the host system to /app in the container. This will allow you to work on the source code in your project's folder and changes will be reflected in the container file-system (in our case /app) without executing any other commands.

Conclusion

In this tutorial, we've seen how to use Docker to create a development environment with Laravel 6. We've seen how to use both Docker and docker-compose to run our Laravel 6 application in an isolated container.

=========================

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter

How To Set Up Laravel, Nginx, and MySQL with Docker Compose

Deploying a Laravel app in Kubernetes on Google Cloud

Docker Basics: Docker Compose

Laravel 6 CRUD Application Tutorial

Laravel 6 Image Upload Tutorial

How to use form validation in Laravel 6

Laravel API Response - Simple Laravel API response wrapper

Laravel API Response - Simple Laravel API response wrapper

Laravel API Response is a good package that we can use to create API responses easily.

Simple and ready to use API response wrapper for Laravel - Simple Laravel API response wrapper.

Installation
  1. Install package through composer: $ composer require obiefy/api-response
  2. publish config file : php artisan vendor:publish --tag=api-response
Basic usage

Create and return JSON response:

use Obiefy\API\Facades\API;
...
public function index()
{
    $users = User::all();
return API::response(200,'users list', $users);

}

Or you can use helper function:

use Obiefy\API\Facades\API;
...
public function index()
{
$users = User::all();

return api()-&gt;response(200, 'users list', $users);

}

Advanced usage

1. General example

use Obiefy\API\Facades\API;
...
public function index()
{
$users = User::all();

return API::response(200, 'users list', $users);

}

result:

{
"STATUS": 200,
"MESSAGE": "users list",
"DATA": [
{"name": "user name"}
]
}

2. Success response

return api()->ok('Success message`, [
'name' => 'Obay Hamed'
]);

result:

{
"STATUS": 200,
"MESSAGE": "Success message",
"DATA": {"name": "Obay Hamed"}
}

you can also return success message with out passing parametters

return api()->ok();

in this case response message will be the default message from config file config('api.messages.success') the same thing for api()->notFound() and api()->validation().

Source Code: https://github.com/obiefy/api-response

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow me on Facebook | Twitter

Further reading

Laravel 5.8 Tutorial for Beginners

Tutorial Laravel 6 with Docker and Docker-Compose

How to Laravel 6 Database Migrations - Add Admin Role to Users

Laravel 6 Release New Features and Upgrade

Laravel 6 CRUD Application Tutorial