dev

Rest API Tutorial Php: Creating Standalone And Simple API For Beginner

I made this REST API tutorial Php for beginners, maybe sometimes it can be a useful snippet for me, but hopefully, it...

· 4 min read >
qarao.com-rest-api-tutorial-php

I made this REST API tutorial Php for beginners, maybe sometimes it can be a useful snippet for me, but hopefully, it can also be useful for those of us who are still learning to code with PHP.

The title might be a bit overkill since we’re actually going to build a simple API because we don’t need all the REST functions ✌️

For this purpose, we only need one PHP file and use a simple MySQL database. This standalone file is for displaying results only. A unique API that actually uses another API. There is no OOP (Object Oriented Programming), procedural code only.

We can also use it to manage output from other sources such as Corona Virus data, and then insert it into our database and display the desired results or widgets in WordPress or our frontend.

What is API?

API (Application Programming Interface) is a set of functions or software code that allows applications to access data and interact with external software components, operating systems, or microservices.

We can think of APIs like vehicles and bridges. Vehicles are the data used and the bridge is the API. The bridge is likened to connecting two different cities, and this type of vehicle can be either a truck or a bus.

So what we can relate to is a vehicle (XML or JSON) and two different cities (Java platform, mobile application, web, both Windows or Linux operating system). Yes, I am using my own words, confused right? but I hope it can be understood 🤣

Database

First, we create a simple Mysql database for this API. Here is my simple schema. It’s all about Covid19 data from WHO. As we know that WHO not directly provide an open API so here we can also use another service.

CREATE DATABASE covid_db;
DROP TABLE IF EXISTS `covid_fix`;
CREATE TABLE `covid_fix` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `country` varchar(50) DEFAULT NULL,
  `cases` int(11) DEFAULT '0',
  `todayCases` int(11) DEFAULT '0',
  `deaths` int(11) DEFAULT '0',
  `todayDeaths` int(11) DEFAULT '0',
  `recovered` int(11) DEFAULT '0',
  `active` int(11) DEFAULT '0',
  `critical` int(11) DEFAULT '0',
  `casesPerOneMillion` int(11) DEFAULT '0',
  `deathsPerOneMillion` int(11) DEFAULT '0',
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;

We can import or run SQL using PHPMyadmin or a client base like TablePlus. Just what I need, for simplicity.

Another story  Installing Lets Encrypt Is Not Difficult At All! You Just Need To Know Ubuntu Version And This Command

But if you want a more complete reference, there are many more open API providers we can use such as here.

Localhost

Second, we need a server for development and luckily PHP has a local server natively via terminal or console, for example using php -S localhost:8989 command.

We can also use Xampp or Wamp for development on local machines. If using the console (terminal), we have to point to the root directory where our index.php is located.

qarao.com-rest-api-tutorial-php-localhost
Local Server via Php

If we have several projects, use different port numbers after localhost command. Next open VSCode to edit our code.

If you need a challenge we can also use the terminal or console to write code, believe me, it feels like we are hackers if we code on this black and white screen LOL!

The Code

Of course, we need to connect to our database. Here is a simple snippet to connect to, as usual, we start with PHP tag <?php on the top.

<?php
date_default_timezone_set('Asia/Jakarta');
$conn = mysqli_connect("localhost", "your_db_user", "your_password", "your_db_name");

// your logic ..

// the important to ouput in JSON format
header('Content-type:application/json;charset=utf-8');
echo json_encode($d);

Where is the logic? As standalone PHP we use query string for that purpose, so here is a logic snippet to get all global covid data.

//
// .. other code    
$s= "SELECT * FROM covid_fix WHERE LOWER(country) != 'global_data' AND DATE(updated_at) = curdate() ORDER BY cases DESC";

$q = mysqli_query($conn, $s);
$d = array();

while ($r = mysqli_fetch_array($q, MYSQLI_ASSOC)) {
 $d[] = $r;
}
// .. other code
//

And here is the complete code

<?php
date_default_timezone_set('Asia/Jakarta');
$conn = mysqli_connect("localhost", "your_db_user", "your_password", "your_db_name");

if (isset($_GET['q'])) {
  // endpoint
  if (strtolower($_GET['q']) == 'indonesia') {
    #get indonesia only
    $s = "SELECT id,country,active,cases,deaths,recovered,todayDeaths as new_deaths,todayCases as new_cases,updated_at as entry_date FROM covid_fix WHERE DATE(updated_at) = curdate() AND LOWER(country) = 'indonesia' order by entry_date desc LIMIT 1";
    //echo $s;die;
    $q = mysqli_query($conn, $s);
    $d = mysqli_fetch_array($q, MYSQLI_ASSOC);
  }

  if (strtolower($_GET['q']) == 'global') {
    #get indonesia only
    $s = "SELECT id,country,active,cases,deaths,recovered,todayDeaths as new_deaths,todayCases as new_cases,updated_at as entry_date FROM covid_fix WHERE DATE(updated_at) = curdate() AND LOWER(country) = 'global_data' order by entry_date desc LIMIT 1";
    //echo $s;die;
    $q = mysqli_query($conn, $s);
    $d = mysqli_fetch_array($q, MYSQLI_ASSOC);
  }

  if (strtolower($_GET['q']) == 'history_indonesia') {
    #get indonesia only
    $s = "SELECT * FROM covid_fix WHERE LOWER(country) = 'indonesia' ORDER BY DATE(updated_at) ASC";
    $q = mysqli_query($conn, $s);

    $d = array();

    while ($r = mysqli_fetch_array($q, MYSQLI_ASSOC)) {
      $d[] = $r;
    }
  }

  if (strtolower($_GET['q']) == 'history_global') {
    #get global history
    $s = "SELECT * FROM covid_fix WHERE LOWER(country) = 'global_data' ORDER BY DATE(updated_at) ASC";
    $q = mysqli_query($conn, $s);

    $d = array();

    while ($r = mysqli_fetch_array($q, MYSQLI_ASSOC)) {
      $d[] = $r;
    }
  }

  if (strtolower($_GET['q']) == 'all') {
    #get all
    $s    = "SELECT * FROM covid_fix WHERE LOWER(country) != 'global_data' AND DATE(updated_at) = curdate() ORDER BY cases DESC";
    $q    = mysqli_query($conn, $s);

    $d = array();

    while ($r = mysqli_fetch_array($q, MYSQLI_ASSOC)) {
      $d[] = $r;
    }
  }
  //echo $s;die;

  #chart idn/global
  if (strtolower($_GET['q']) == 'chart_indonesia' || strtolower($_GET['q']) == 'chart_global') {

    $country = 'Indonesia';
    if (strtolower($_GET['q']) == 'chart_global') $country = 'GLOBAL_DATA';

    $s    = "SELECT DATE_FORMAT(DATE(updated_at), '%b %d') AS tgl, cases AS kasus, 
             todayCases as kasus_baru, active AS dirawat, deaths AS meninggal, todayDeaths AS meninggal_harian, 
             recovered AS sembuh FROM covid_fix 
             WHERE country = '$country' AND DATE(updated_at) < curdate() ORDER BY DATE(updated_at)";
    $q    = mysqli_query($conn, $s);

    $d = array();

    $kasus            = "";
    $tgl              = "";
    $kasus_baru       = "";
    $dirawat          = "";
    $meninggal        = "";
    $meninggal_harian = "";
    $sembuh           = "";
    while ($r = mysqli_fetch_array($q, MYSQLI_ASSOC)) {
      $kasus            .= $r['kasus'] . ",";
      $dirawat          .= $r['dirawat'] . ",";
      $kasus_baru       .= $r['kasus_baru'] . ",";
      $meninggal        .= $r['meninggal'] . ",";
      $meninggal_harian .= $r['meninggal_harian'] . ",";
      $sembuh           .= $r['sembuh'] . ",";
      $tgl              .= "'" . $r['tgl'] . "'" . ",";
    }

    $d = array(
      'tgl'               => rtrim($tgl, ","),
      'kasus'             => rtrim($kasus, ","),
      'kasus_baru'        => rtrim($kasus_baru, ","),
      'dirawat'           => rtrim($dirawat, ","),
      'meninggal'         => rtrim($meninggal, ","),
      'meninggal_harian'  => rtrim($meninggal_harian, ","),
      'sembuh'            => rtrim($sembuh, ","),
    );
  }

} else {

  $site = "http://localhost:8989";
  // intro
  $d = array(
    'deskripsi'   => 'COVID-19',
    'endpoint_0'  => $site . '/?q=all',
    'endpoint_1'  => $site . '/?q=indonesia',
    'endpoint_2'  => $site . '/?q=global',
    'endpoint_3'  => $site . '/?q=history_indonesia',
    'endpoint_4'  => $site . '/?q=history_global',
    'endpoint_5'  => $site . '/?q=chart_indonesia',
    'endpoint_6'  => $site . '/?q=chart_global',
  );
}

header('Content-type:application/json;charset=utf-8');
echo json_encode($d);

//End of File

As you can see I host this simple API to my subdomain here st.qarao.com/covid this actually the URL for the widget on this blog before.

Another story  How To Host Multiple Domain In One Droplet In DigitalOcean VPS

NOTE: At the time of writing, COVID-19 remains a common health problem for us. So stay healthy and wear a mask guys. 😷

Leave a Reply

Your email address will not be published. Required fields are marked *

Right Menu Icon