PHP APIs With The Slim Framework

PHP Code Snippets APIs With The Slim Framework
Share:

About

In this code snippet, we’ll make a REST API with the Slim framework in PHP.

Slim is a framework that enables you to easily and quickly build REST APIs in PHP. I will show you how to make a POST and GET endpoint. Other types of requests follow the same logic. Official dodumentation here. We will also enable CORS so you can call the API from the browser.

Let’s see the example below.

Installing Slim:

Install Slim using Composer by opening your project directory in cmd and running this: 

composer require slim/slim:^4.8

followed by this: 

composer require slim/psr7

If you don’t know what Composer is or how to use it check out this post I made.

Code:

<?php

//Include needed files///////////////////////////////////////////

use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;

require __DIR__ . '\vendor\autoload.php';

/////////////////////////////////////////////////////////////////

//Setup API////////////////////////////////////////////////////// 

//Create the API instance.
$app = AppFactory::create();
//Get the current script path and set it as base path for Slim API.
$app->setBasePath($_SERVER['SCRIPT_NAME']);
//Any errors that occour will be handled and nicely displayed by Slim.
$app->addErrorMiddleware(true, true, true);
//With slim v4 you need to add this to be able to get the POST body with getParsedBody(). Else it will be null.
$app->addBodyParsingMiddleware();

//Variables.
$apiKey = "mysupersecurekey";

//CORS Enable//////////////////////////////////////////////////////

//Enabling CORS allows you to make requests to this API from a web browser.

$app->options('/{routes:.+}', function ($request, $response, $args) {
    return $response;
});

$app->add(function ($request, $handler) {
    $response = $handler->handle($request);
    return $response
            ->withHeader('Access-Control-Allow-Origin', '*') //Set a specific url where you want to enable cors. If left like so CORS will be enabled for all domains.
            ->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization')
            ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS');
});

///////////////////////////////////////////////////////////////////

//Add endpoints////////////////////////////////////////////////////


//Simple GET request endpoint.
$app->get('/hello/{name}', function (Request $request, Response $response, array $args) {
    $name =  $args['name'];
    $response->getBody()->write("Hello, $name");
    return $response;
});


//POST request endpoint that takes in and returns json.
//When you make the endpoint you can pass in variables with use().
$app->post('/userdata', function ($request, $response, $args) use($apiKey){

    //Get JSON from the body of the request.///////////////////////////////////////////

    $requestJSON = $request->getParsedBody();

    ///////////////////////////////////////////////////////////////////////////////////


    //Check if the api key is present and correct./////////////////////////////////////

    if(!array_key_exists("key", $requestJSON)){
        $responseBody =  array('message' => 'Missing API key.');
        return $response->withHeader('Access-Control-Allow-Origin', '*')
                        ->withHeader("Access-Control-Allow-Methods", "POST, OPTIONS")
                        ->withJson($responseBody, 400);
    }
    
    if($apiKey != $requestJSON["key"]){
        $responseBody =  array('message' => 'Invalid API key.');
        return $response->withHeader('Access-Control-Allow-Origin', '*')
                        ->withHeader("Access-Control-Allow-Methods", "POST, OPTIONS")
                        ->withJson($responseBody, 400);
    }

    ///////////////////////////////////////////////////////////////////////////////////


    ///////////////////////////////////////////////////////////////////////////////////

    //Buisness logic here ...
    //Lets pretend to add the user to the DB...

    //Make a response.
    $responseData = "{ \"Message\" : \"User was added.\"}";
    
    ///////////////////////////////////////////////////////////////////////////////////


    //Return response//////////////////////////////////////////////////////////////////

    //Add response data.
    $response->getBody()->write($responseData);
    
    //Add headers and return the response.
    return $response->withHeader('Content-Type', 'application/json');

    ///////////////////////////////////////////////////////////////////////////////////
});

///////////////////////////////////////////////////////////////////////////////////////

//Add '/{routes:.+}' as last route. (Part of enabling CORS)
$app->map(['GET', 'POST', 'PUT', 'DELETE', 'PATCH'], '/{routes:.+}', function ($request, $response) {
    throw new HttpNotFoundException($request);
});

//Run the API instance.
$app->run();

////////////////////////////////////////////////////////////////////////////////////////

Resulting Output:

Share:

Leave a Reply

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

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger