This topic is locked

PHPRunner APP client RESTful API

4/27/2020 7:07:01 AM
PHPRunner Tips and Tricks
fhumanes author


This image reflects the main uses of REST services. As you can see there are 2 ways to use them.
(1) .- It is the most common way. APP applications (Android and IOS) consume the data and business objects offered by company servers. Also, browsers (Chrome, Firefox, MS Edge, Safari, Opera, etc.) are clients of these services, using these from the javascript language.
(2) .- This is the form that PHPRunner uses. In this case it is a server application (PHP) that uses the services to later present the data in a browser.
RESTfull API service release
Practically all public administrations have their open data publications and it is quite normal that they be offered in JSON format.
https://datos.gob.es/ is the website of these data from the government of Spain.
There are also other companies that offer data that they collect and to facilitate their use, they offer it through this protocol / architecture.
https://rapidapi.com/ is an example and is where I have accessed data from a free service that offers COVID 19 data from around the world.
https://rapidapi.com/api-sports/api/covid-193
What does the example have?
What the application wants to show is a complete example that shows the new functionalities that version 10.4 incorporates, that is where I will extend more, so that it can be of help to those of you who wish to try these functionalities.
Also, and as a complement, I will show you that we can access this data and show it in "temporary" tables and you will appreciate that everything works very fast. This functionality can also be important because it does not require version 10.4 and can be used from any version of PHPRunner.
The Server has 3 methods:
Coutries. Provide the name of all countries.

Statistics. It facilitates the current situation of Covid 19 in all countries.

History. Provide the information of any country as of a date before today.


As shown in the figure, there are the menu options that use the new functionality in version 10.4 and the other set of options that uses a "temporary" table to display the recovered data from RESTfull Api.
DEMO: https://fhumanes.com/covid_19
Explanations of the new features in version 10.4


(1).- The service connection must be defined. In this case, the data is shown in this image.


(2).- Once we have the connection we must start defining REST views, according to the methods that the service offers us and that we want to use in the application.
(3).- This popup screen appears and the name must be assigned. Typically, it matches the name of the service method.
(4).- When we want, once we have created the view, go to its definition, select the view (by clicking on it) and press the "Next" button at point (5).


(1).- We can select the resource that we want to configure.
(2).- In the different tabs each of the actions on the resource is configured. In the example, only "list" and "single" (3) are configured, which become "list" and "view" of the tables.
(4).- From that button you can go to the Resource configuration and its security system.
(5).- The method of the Resource is indicated. If it had parameters for GET, they would also go there. In the case of the "history" method there will go "history? Country =: {search.country} & day =: {search.day}", to indicate that the parameters of "country" and "day" are passed. In this case we collect them from the search panel.
(6).- If the request is by PUT, at this point the parameters will go.
(7).- This button tests the request and will show the response of the service in point (8).
(8).- Shows the response to having pressed the button (7). The (+) symbol and the "clipboard" are very important. With the (+) the field is added in the list (9) and with the "clipboard" that will mainly be used in the configuration of "single", it carries the transformation ptah of the access to the JSON data.
(9).- It is the list of fields that we want to deal with in the "list" action. From there we can modify what you have copied automatically by pressing the (+) button.


(3).- It is the name of the field to be used in the design part, etc.
(4).- It is the type depending on the value of that field. It also marks the way of presentation in design.
(5).- It is the access path to the JSON for LIST. It is better to leave what the system puts automatically when you press the "+" (1).
(6).- It is the access path to the SINGLE JSON. In this case you have to do the test, "Run request" button and using the "clipboard" button (2) copy the value and paste in point (6).
Explanation of how to access data without version 10.4
In order to access the data of a RESTfull API, I have used a PHP library "unirest" version 3.0.4, which is the one recommended by the web https://rapidapi.com/.
You may encounter a problem when accessing with HTTPS protocol and this is because in your PHP configuration file "php.ini" this section must be completed.



[curl]

; A default value for the CURLOPT_CAINFO option. This is required to be an

; absolute path.

;curl.cainfo =

curl.cainfo="C:/PHP/certficados/cacert.pem"


You can download this file from CA (Certification Authorities) authorized from https://curl.haxx.se/ca/cacert.pem
This form of access to RESTfull API resource data can be used from any version of PHPrunner, since it only depends on the PHP version and in this case, I think, it requires version 5.3
Since we are going to use tables to present the data, it is important:

  • That the storage system of the tables is "MyISAM" and not "innoDB". Tables "MyISAM" are very fast to load and delete records.
  • I use the "SessionName" field, with the name of each user's session so that even though the data is in the same table, each user has their own data.


I show some examples.
get_cuntries.php



<?php

@ini_set("display_errors","1");

@ini_set("display_startup_errors","1");

require_once __DIR__ . '/../../ComponentCode/unirest_3.0.4/autoload.php';

$session_name = session_id();

// Consultar si ya están cargados | Check if they are already loaded

$sql=" SELECT count(*) row_num FROM covid_country where SessionName = '$session_name' ";

$resql=db_query($sql,$conn);

$row=db_fetch_array($resql);

if ($row['row_num'] == 0) { // Load Conuntry in session

// Delete the Countries of session

$sql="delete FROM covid_country where SessionName = '$session_name' ";

$resql=db_query($sql,$conn);

$response = Unirest\Request::get("https://covid-193.p.rapidapi.com/countries",

array(

"X-RapidAPI-Host" => "covid-193.p.rapidapi.com",

"X-RapidAPI-Key" => "4bc3052c61msh7345bc8ec10474ap10192ejsn016e636a3859"

)

);

$a = $response->code; // HTTP Status code

$b = $response->headers; // Headers

$c = $response->body; // Parsed body

$d = $response->raw_body; // Unparsed body

$f = json_decode($d,true);

// var_dump($f); // DUMP pf array

$count = count($f["response"]);

foreach($f["response"] as $response) {

$country = $response;

$sql="insert INTO covid_country (SessionName,Country) VALUES ('$session_name','$country') ";

$resql=db_query($sql,$conn);

}

} // End row_num == 0


get_statistics.php



<?php

@ini_set("display_errors","1");

@ini_set("display_startup_errors","1");

require_once __DIR__ . '/../../ComponentCode/unirest_3.0.4/autoload.php';

function valueToZero($val){

return empty($val)?0:$val;

}

$session_name = session_id();

// Delete the covid_statistics of session

$sql="delete FROM covid_statistics where SessionName = '$session_name'";

$resql=db_query($sql,$conn);

$response = Unirest\Request::get("https://covid-193.p.rapidapi.com/statistics",

array(

"X-RapidAPI-Host" => "covid-193.p.rapidapi.com",

"X-RapidAPI-Key" => "4bc3052c61msh7345bc8ec10474ap10192ejsn016e636a3859"

)

);

$a = $response->code; // HTTP Status code

$b = $response->headers; // Headers

$c = $response->body; // Parsed body

$d = $response->raw_body; // Unparsed body

$f = json_decode($d,true);

// var_dump($f); // DUMP pf array

$count = count($f["response"]);

foreach($f["response"] as $response) {

// $SessionName,

$country = $response['country'];

$day = $response['day'];

$CasesNew = $response['cases']['new'];

$CasesActive = $response['cases']['active'];

$CasesCritical = $response['cases']['critical'];

$CasesRecovered = $response['cases']['recovered'];

$CasesTotal = $response['cases']['total'];

$DeathsNew = $response['deaths']['new'];

$DeathsTotal = $response['deaths']['total'];

$TestTotal = $response['tests']['total'];



$CasesNew = valueToZero($CasesNew); // if Null = 0

$CasesActive = valueToZero($CasesActive); // if Null = 0

$CasesCritical = valueToZero($CasesCritical); // if Null = 0

$CasesRecovered = valueToZero($CasesRecovered); // if Null = 0

$CasesTotal = valueToZero($CasesTotal); // if Null = 0

$DeathsNew = valueToZero($DeathsNew); // if Null = 0

$DeathsTotal = valueToZero($DeathsTotal); // if Null = 0

$TestTotal = valueToZero($TestTotal); // if Null = 0

$sql="insert INTO covid_statistics

(SessionName,country,dataDay,CasesNew,CasesActive,CasesCritical,CasesRecovered,CasesTotal,DeathsNew,DeathsTotal,TestTotal)

VALUES ('$session_name','$country','$day',$CasesNew,$CasesActive,$CasesCritical,$CasesRecovered,$CasesTotal,$DeathsNew,$DeathsTotal,$TestTotal)";

$resql=db_query($sql,$conn);



}



In the "History" method, we see that it presents the panel with the "country" and "Day" fields. The Country field has a lookup of the resource "Countries" defined. I could not indicate that "Day" has the date type because the parameter requires the format "yyyy-mm-dd", example, 2020-04-26, and I have not known how to configure it.
In my portal I leave all the code so that you can install it on your computers.
For any questions or precision, contact me through the email [email="fernandohumanes@gmail.com"]fernandohumanes@gmail.com[/email]

K
KingDean 6/3/2020

Fernando, this is very helpful. Thanks for putting this together. I really like having the graphics along with a great walk-through of the process, as a beginner it really helps tremendously.

Max 10/21/2020

Great job Fernando.

H
hvilberg 1/29/2021

This is most helpful and a very detailed tutorial <img src='https://asprunner.com/forums/file.php?topicimage=1&fieldname=reply&id=93719&image=1&table=forumreplies' class='bbc_emoticon' alt=':)' />
However I'm looking for a method that uses the built in Rest API in 10.5 - Is there any way to copy results from the API connection to a table instead of fetching results every time the list page is loaded?

fhumanes author 2/1/2021

Hello:
This example is written for phprunner 10.4 but it also works on 10.5.
It shows 2 types of execution and consumption of a REST API.

  • Using the standard connection method each time, which makes you the PHPRunner standard.
  • Another way to consume the service and store the response in a table and from it, exploit the result (which could be applied to any version of PHPRunner -even prior to 10.4-).
    I believe that the method of the 2nd form of consumption of the service is what you are looking for.
    Greetings,

    fernando

S
salus1DevClub member 2/5/2021

Hi,
Excellent tutorial. I had a similar question about writing API query results to database fields.
Take a look at https://asprunner.com/forums/topic/28112-writing-view-as-custom-result-to-field/
Best regards

S
stoneiii 3/5/2021

I am trying to create a custom button that will save API view data to a database table. I would like the user to be able to select a group of records in a list view of a database table and then save the API data into a detail table. A parameter for the API View needs to come from a field in the selected grid rows .

My use case is to allow a user to import a list of VIN numbers to a table. Then select some or all of the VIN numbers in the list, click the custom button to save all the VIN data from the NHTSA API into a VIN detail database table. Has anyone else done this? Any help would be much appreciate!
Thank you