user12865281
user12865281

Reputation:

How to create a json php api that only connects given with the expo react native app?

I have the following PHP code where I intend to convert it into an API to show my sports news that is hosted in a PHP application and the data stored in MYSQL, so I want to show those records of my news in an application developed in Expo React Native.

$stmt = $con->prepare("SELECT
                            url,
                            cover_page,
                            alt_img,
                            mini_title,
                            mini_description,
                            date_post,
                            confg_img,
                            main_cover
                        FROM news ORDER BY id_news DESC LIMIT 5");

    //$stmt->bind_param("i", $id);
    $stmt->execute();
    $member = array();
    $stmt->bind_result(
        $member['url'],
        $member['cover_page'],
        $member['alt_img'],
        $member['mini_title'],
        $member['mini_description'],
        $member['date_post'],
        $member['confg_img'],
        $member['main_cover']
    );

    //Los {}corchetes " " especifican un objeto y " []" se utilizan para matrices de acuerdo con la especificación JSON.
    header('Content-Type: application/json');
    //header('Content-type: application/json; charset=utf-8');
    echo '[';
    $count = 0;
    while ($stmt->fetch()) {
        if( $count ) {
            echo ',';
        }

        //echo json_encode($member, JSON_UNESCAPED_SLASHES);
        echo json_encode($member, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_FORCE_OBJECT);

        ++$count;
    }

    echo ']';

The code already generates a JSON structure for me, printing the data in JSON in such a way:

   [{
        "url": "es/deportes/futbol/ecuador/ligapro/serie-a/679/oscar-bagui-es-el-hombre-record-en-emelec",
        "cover_page": "https://i.imgur.com/UI5IaZ5.jpg",
        "alt_img": "Oscar Bagui ",
        "mini_title": "Oscar Bagui es el hombre r\u00e9cord en Emelec",
        "mini_description": "El defensa el\u00e9ctrico sigue siendo importante para los el\u00e9ctricos",
        "date_post": "2020-12-13 21:24:37",
        "confg_img": null,
        "main_cover": "featured_news"
    },{
        "url": "es/deportes/futbol/ecuador/ligapro/serie-a/675/la-dirigencia-de-liga-de-quito-quiere-cerrar-el-fichaje-de-este-jugador-del-extranjero",
        "cover_page": "https://i.imgur.com/7p6l5ZA.jpg",
        "alt_img": "Posible fichaje de Liga de Quito desde la MLS",
        "mini_title": "La dirigencia de Liga de Quito quiere cerrar el fichaje de este jugador del extranjero",
        "mini_description": "Los albos quieren potenciar su plantilla para 2021",
        "date_post": "2020-12-13 13:56:45",
        "confg_img": null,
        "main_cover": "relevant_news"
    }]

But I this route example.com/api/json.php I have to create a code, a key that allows only the connection with the application only the app that has the access key with the application will show the data, this key in some Examples that I have seen, I realize that some parameters pass through the url.

So my question is, how to print the data in expo react native but that the data call is linked with a key between the app and the api json php

Upvotes: 2

Views: 479

Answers (4)

Ken Lee
Ken Lee

Reputation: 8073

First , in your app , you have a secret key (e.g. Stackoverflow1234#@$%x) which nobody knows.

and in your php, you can use this

<?php

if ( isset($_REQUEST['key']) && $_REQUEST["key"]== "Stackoverflow1234#@$%x") {

/// codes to connect to your DB and generate the JSON


}
?>

and in your react-native app, you can use https://www.yourdomain.com/xxx.php?key=Stackoverflow1234#@$%x to get the data, such as:


 return fetch('https://www.yourdomain.com/xxx.php?key=' + secretkey)
         .then((response) => response.json())
         .then((responseJson) => {
           this.setState({
             retrievedata: responseJson          
             
           }, function() {
             // In this block you can do something with new state.
                          
           });
         })
         .catch((error) => {
           console.error(error);
         });

Upvotes: 0

Marcel
Marcel

Reputation: 5119

Based on Arnold Daniels answer here 's the part for your react request.

fetch('example.com/api/json', {
    method: 'POST',
    headers: {
        'Authorization': 'Bearer ' + btoa('username:password'),
    },
    body: ...
});

The username:password combination is just an example. Instead of the username password combination you can use every encoded string you want. It must be valid with the token on your backend (PHP) side.

Upvotes: 1

Arnold Daniels
Arnold Daniels

Reputation: 16573

What you're looking for is called Bearer Authentication. With bearer authentication, the user must send a token in the Authorization HTTP Header in order to use the API.

Authorization: Bearer <token>

In PHP this header will be available as $_SERVER['HTTP_AUTHORIZATION'].

You can extract the token an verify it against the database.

[$type, $token] = explode(' ', $_SERVER['HTTP_AUTHORIZATION'] ?? '', 2) + ['', ''];

if (strtolower($type) !== 'bearer' || !validate_token($token)) {
    http_response_code(403); // forbidden
    echo "Missing or invalid Bearer authentication";
    exit();
}

Upvotes: 3

ucup
ucup

Reputation: 685

php ==>

if(!isset($_POST['Key'])){
//return error json code (you dont have access)
}

react native ==>

 fetch('example.com/api/json.php', {
  method: 'POST',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    Key: 'yourKey'
  })
});

you can also specify the the key in the php code

if($_POST['Key']!=='Your key'){
  //return json error code (key doesnt match)
}

Upvotes: 0

Related Questions