Skip to content

Instantly share code, notes, and snippets.

@tashirka1
Forked from nasrulhazim/apidev-01.md
Created April 19, 2017 18:37
Show Gist options
  • Save tashirka1/3fcf1096f460f509fbfc0cd43e8e43a2 to your computer and use it in GitHub Desktop.
Save tashirka1/3fcf1096f460f509fbfc0cd43e8e43a2 to your computer and use it in GitHub Desktop.
API Basic

API Development with Vanilla PHP

In this tutorial, just want to expose the basic of API Development with plain PHP.

You should install https://www.getpostman.com/ before proceed with this tutorial.

Objectives

  1. Understand what is the headers
  2. Understand the Content-Type
  3. Understand the Accept
  4. Return Responses
  5. Basic Error Handling

Create a new php file called funcs.php in any folder. Then add the following at the top of the file.

function dump($dump)
{
    echo '<pre>' . print_r($dump, 1) . '</pre>';
}

This basically just to output nice debug message.

Header

Create a file named headers.php and copy paste the following.

<?php

require_once 'funcs.php';

$headers = getallheaders();

dump($headers);

In your directory, run php -S localhost:8000. This command will run the PHP Web Server to server your current directory.

Now open up your browser or in Postman and enter http://localhost:8000/headers.php.

You should have response like the following:

Array
(
    [Host] => localhost:8001
    [Connection] => keep-alive
    [Cache-Control] => no-cache
    [User-Agent] => Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36
    [Postman-Token] => 4cf519e5-64f2-f2a6-f727-4e2b3132333c
    [Accept] => */*
    [Accept-Encoding] => gzip, deflate, sdch, br
    [Accept-Language] => en-GB,en;q=0.8,en-US;q=0.6,ms;q=0.4,id;q=0.2
)

From these headers, you can check, which headers are compulsary in order to access to the API. Common required headers are:

  1. Accept
  2. Content-Type
  3. Authorization

Response

Nowadays, the common response from an API is JavaScript Object Notation (JSON) or eXtensible Markup Language (XML).

In this tutorial, we going to use JSON, because it's simplicity and clean structure.

API Responses not limit to JSON / XML only, it can be images, videos, etc.

Now, create a file named response.php and add the following codes

<?php

require_once 'funcs.php';

// response('some data');
// response(['some' => 'data']);
// response(true);
response([1, 2, 3, 4]);
// response('ops! something went wrong!', true, 400);

function response($value, $error = false, $code = 200)
{
    // return output as json, instead of text/html
    header('Content-Type: application/json');

    // set http status code
    http_response_code($code);

    // handle error output
    if ($error) {
        // convert to JSON format and echo
        echo json_encode([
            'error' => true,
            'message' => $value,
            'status' => $code,
        ]);
        return;
    }

    // normal output, with standard format
    $output = [
        'data' => $value,
    ];

    // convert to JSON format and echo
    echo json_encode($output);
}

Now open up your browser or in Postman and enter http://localhost:8000/response.php.

You can comment and uncomment sample codes from line 16 to 20 to see different results.

HTTP Request Method

There's two common HTTP Request Method being used:

  1. GET
  2. POST

Some others being used is:

  1. PUT
  2. PATCH
  3. DELETE

Here a simple script that can check if the request is a valid HTTP Request Method.

<?php

require_once 'funcs.php';

if (validMethodRequest()) {
    dump($_SERVER['REQUEST_METHOD'] . ' is valid');
} else {
    dump($_SERVER['REQUEST_METHOD'] . ' is invalid');
}

function validMethodRequest()
{
    $allowed_methods = [
        'GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE',
    ];

    if (in_array($_SERVER['REQUEST_METHOD'], $allowed_methods)) {
        return true;
    }

    return false;
}

Now open up your Postman and enter http://localhost:8000/request.php.

Try to change the HTTP Method Request (to the left of the URL input), then submit.

You will get COPY is invalid if you use request for COPY, but you will get GET is valid if you change to GET method.

HTTP Request Method is important in order to control, which request is use for CRUD operation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment