Starting Your API Endpoint with PHP

By: Bobby

Published on: Mar 30, 2023

3 min read.

Last time we convened, we got down and dirty with (https://catchylabs.com/2023/03/setting-up-a-new-website-on-your-lamp-stack/)[setting up a new website] on our ready-and-raring-to-go LAMP stack. Now that our server is primed and prepped for service, we’re going to ramp things up a notch. We are delving into the process of creating an API endpoint using PHP. Before we dive into the code, we need to broach the topic of Apache’s mod-rewrite module and its trusty sidekick: the .htaccess file.

You can think of the Apache mod-rewrite as the backstage crew of a theatre production. It operates behind the scenes, silently directing HTTP traffic to its correct destination. Mod-rewrite uses .htaccess, a directory-level configuration file, to rewrite URL requests. This pair works hand in glove to ensure your API requests get parsed correctly. To elucidate, let’s look at our .htaccess rules:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?request=$1 [QSA,NC,L]

Start Header and Error Reporting

To start off our PHP script, we’ll first set the HTTP header and error reporting preferences. The header function is our first port of call, with this function you’re instructing the server to return a raw HTTP header that informs the client they will receive data in JSON format.

Our next stop is to turn off error displaying on-screen and instead route them to a log file for later debugging. This approach helps keep the user interface clean and uncluttered by pesky PHP errors.

<?php
header("Content-Type: application/json; charset=UTF-8");

ini_set('display_errors', 0);
ini_set('log_errors', 1);
error_reporting(E_ALL);

Initial Variables

Now, let’s get to the meat of the matter. The $request variable is set to the ‘request’ GET parameter, which may seem quite ordinary. However, if you recall the .htaccess rules we set earlier, it becomes clear that this works in conjunction with them.

When a client sends a request to the server that doesn’t map to an existing file or directory, the .htaccess rules kick in. The rule takes the request and rewrites it to ‘index.php?request=…’, which makes the original request available within our script. This mechanism enables you to handle all kinds of requests through a single script.

$request = $_GET['request'];
$return = array('code' => 200, 'message' => '');

API Key Check

Our script now needs a gatekeeper. This is where the API key check comes into play. This step introduces a straightforward method of access control. We simply deny any requests that do not carry the correct ‘s-authorization’ header. If you’re thinking that this could be improved, you’re right!

In this example, we use a hardcoded API key. This is purely for demonstration purposes. In a full-fledged application, you can replace this with a robust system that checks individual session tokens for users.

$api_key = 'your-test-api-key';
$headers = apache_request_headers();

if ( isset($headers['x-authorization']) ) {
  if ( $api_key != 'your-valid-api-key' ) {
    http_response_code(401);
    echo json_encode(array("message" => "Invalid API Key."));
    exit();
  }
} else {
  http_response_code(401);
  echo json_encode(array("message" => "API Key Required."));
  exit();
}

The Endpoint Switch

Our script is all geared up to handle requests. Depending on the ‘request’ parameter, the switch statement will steer the code execution in the right direction.

Here, we have two cases, ‘test’ and ‘default’, which return different responses. This structure is the bedrock of your API’s functionality. As your application expands, you can add as many endpoints as you need, each one handling a different aspect of your application’s logic.

switch ($request) {
  case 'test':
    $return = array('code' => 200, 'message' => 'test.');
  break;

  default: 
    $return = array('code' => 200, 'message' => 'hello.');
  break;
}

exit(json_encode($return));

Using the Endpoint

Now that we have a functional endpoint, we can use it in our React front end. A basic request would look like this:

fetch('https://your-api-endpoint.com/request', {
    headers: {
        'x-authorization': 'your-valid-api-key'
    }
})

Post vars can be added and parsed by our script for robust queries and actions, but we’ll worry about that later.

And there you have it! A bare-bones, yet functional, API endpoint. You can find the complete script over at this GitHub Gist. We hope you found this helpful, and as always, happy coding!

Leave a Reply

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