DEV Community

loading...

My first API using native PHP

theahmedlatif profile image Ahmed AbdElLatif ・2 min read

I tried to create my first API while exercising OOP using php, and here what I achieved, take live look here!

First things First!

I created env.php which includes class Environment to parse my own .env file through public function getDatabaseVariables() in order to capture database variables

#Database#
HOST = "localhost"
DATABASE_SERVICE = "mysql"
DATABASE_NAME = "example_db"
DATABASE_USERNAME = "example_user"
DATABASE_PASSWORD = "example_password"
Enter fullscreen mode Exit fullscreen mode

I followed the below approach to parse .env file using preg_match to detect the first line.

$validate_line_from_env_file = preg_match('~^[a-zA-Z]~',$line);
Enter fullscreen mode Exit fullscreen mode

then make use of explode and strpos to catch variable in an associative array as following:

$env_file_text = explode('= "',$line);
$env_variable_key_length = strpos($env_file_text[0]," ");
$env_variable_key = substr($env_file_text[0],0,$env_variable_key_length);
$env_variable_value_length = strpos($env_file_text[1],"\"");
$env_variable_value = substr($env_file_text[1],0,$env_variable_value_length);
if ($env_variable_value == true)
{
    $this->variables += [$env_variable_key => $env_variable_value];
}
else if ($env_variable_value === "")
{
    $this->variables += [$env_variable_key => ""];
}
Enter fullscreen mode Exit fullscreen mode

Then those variables are passed to class Database that extends class Environment where the __construct() function store the required variables, after that a database connection will be created using PDO.

Query the items

The database connection function is being called through __construct() function of class Museum, where the query statement exists

public function getMuseums()
{
    $sqlQuery = "SELECT id, mname, arabic_name, city, type, est_year, website, coordinates, wikipedia_url FROM " . $this->db_table;
    $statement = $this->conn->prepare($sqlQuery);
    $statement->execute();
    return $statement;

}
Enter fullscreen mode Exit fullscreen mode

Finally!

query is being executed in read.php which present api result in json format.

$statement = $items->getMuseums();
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
$itemCount = $statement->rowCount();

//prepare array for json format
if ($itemCount > 0){
    $museumArray = array();
    $museumArray["itemCount"] = $itemCount;
    $museumArray["body"] = $result;

    echo json_encode($museumArray);
}
else
{
http_response_code(404);
echo json_encode(
    array("message" => "No record found.")
);
Enter fullscreen mode Exit fullscreen mode

last piece: I added the following .htaccess code to prevent accessing other routes except .api/read.php

Order deny,allow
Deny from all

<Files "read.php">
    Allow from all
</Files>
Enter fullscreen mode Exit fullscreen mode

Output sample

Alt Text

You can check this api

on github
or visit the live version


Thanks for your time reading my article!

Discussion (0)

Forem Open with the Forem app