Basic API

Follow the steps below if you need to create an API end point to define the interactions between multiple software.

The REST end point is easily added, with an anonymous method to handle the $request, the anonymous method should have the $response variable. The $request exposes more information which comes from the browser, in the case of parameters passed to it. You should always return the $response object:

Step 1 - Create API file & sub-directories

All your API's must be stored in the API directory. For this example we will make the files and sub-directories for “cars” and “characters”.

Now create php files inside those sub-directories (eg. name the file cars.php and the other characters.php).

Step 2 - Define routes

Now that the API files has been created, we must define our Routes. There are various methods which can be used.

GET Method

In the cars.php file you created, add the following to the script:


<?php

\Tina4\Get::add("/api/cars", function (\Tina4\Response $response) {

    $cars = ["Rolls Royce", "Aston Martin", "Bugatti"];

return $response ($cars, HTTP_OK, APPLICATION_JSON);
});

POST Method


<?php

\Tina4\Post::add("/api/characters", function (\Tina4\Response $response) {
    $characters = ["Clancy Gilroy", "Peter Griffin", "Broden Kelly"];
return $response ($characters, HTTP_OK, APPLICATION_JSON);
});

Other Methods


<?php

//Other methods you can test
\Tina4\Post::add(...);

\Tina4\Patch::add(...);

\Tina4\Put::add(...);

\Tina4\Delete::add(...);

//You guessed it - It takes every method - GET, POST, DELETE, PUT, PATCH, OPTIONS
\Tina4\Any::add(...);

Step 3 - Annotate API

Now we will need to annotate the end point we created. This will be a description of the end point which will be used in Swagger. Its as easy as adding the following lines above the end point you created:


<?php

/**
* @description My first API
* @summary Returns list of cars
* @tags Cars
*/

Step 4 - Test API

Now we can test to check if our API is working. Spin up a Web-Server by running the following command in your IDE terminal:


composer start

Now that the Web-Serveris running, add /swaggerto the URL:

A Swagger page will load and you will see the following which will include the data and annotations within the script created:

Next click on the API and then click on “Try It Out” button. Thereafter, click on the execute button:

You will see the following responses in the browser:

Conclusion

You just created a basic API using Tina4. You are on your way to becoming a serious Code Ninja or Kunoichi. Please reach out to the developers if you have any questions or suggestions.

Powered by ComboStrap