Aleman
Aleman

Reputation: 101

PHP SLIM - how to receive a json format in the body?

I have no idea how to receive JSON that is sent in the body to my API.

I have this lines of code. But it doesn't work.

$app->post('/api/respuestas',function($request) use ($app){
    $json= $request ->getParsedBody();
     $datos= json_decode($json);

   echo "$datos";  // HERE IS THE PROBLEM  NOTHING HAPPENS


   //create sql
     $sql = "
              // sql insert into
          ";


    //execute  sql

    // try {
    //     $db= new db();
    //     $db = $db->connect();
    //
    //     $stmt = $db->query($sql);
    //     $preguntas = $stmt->fetchAll(PDO::FETCH_OBJ);
    //     $db = null;
    //     echo json_encode($preguntas);
    // } catch (PDOException $e) {
    //   echo '{"error":{"text":'.$e->getMessage().'}}';
    // }

});

how to know if I'm really getting the json?

**NEW ** im testin with EasyRest

enter image description here

Upvotes: 0

Views: 882

Answers (2)

Aleman
Aleman

Reputation: 101

Ok i found the solution

CODE

$app->post('/api/respuestas', function($request) {
  $data = $request->getParsedBody();
  $name = $data['product'];

    echo" hello $name" ;

});

POST TEST

enter image description here

source

Upvotes: 1

Pedro Batista
Pedro Batista

Reputation: 181

Could it be a typo?

$json = $request->gerParsedBody(); ^

Replacing gerParsedBody with getParsedBody should work.

Upvotes: 1

Related Questions