Try to post array of objects from postman to php api and get errors

Viewed 1954

I came from Java-Script world and this syntax is strange for me for me.

I try to send post request from postman with body of array of objects like this:

My php code:

<?php
$signatures = $_POST["signatures"];
$signature = array_filter($signatures);
echo json_encode($signature);

But my response from postman is:

enter image description here

3 Answers

The way you are doing this is impossible I assume, you can only transfer strings using POST and GET, try to send all the data in just one KEY and then json_decode it in serve side. So try to send something like this

[
  {
    "id": 1,
    "flowID": 1,
    "fileID": 1,
    "type": "partner",
    "page": 1
  }
]

as VALUE, with KEY: signatures, then in PHP code:

<?php
$signatures = json_decode($_POST["signatures"]); // <=== this is an array now
print_r($signature);

You are trying to filter an array but you did not written how to filter it (second parameter)

    <?php
$signatures = $_POST["signatures"];
$signature = array_filter($signatures,<**variabile or function to be filtered**>);
echo json_encode($signature);

How to send array of objects: Set postman to application/json and post body:

[
    {
        "id": 1,
        "flowID": 1,
        "fileID": 2,
        "type": "identification",
        "page": 1,
        "positionX": 160,
        "positionY": 241,
        "sizeWidth": 150,
        "sizeHeight": 250
    },
        {
        "id": 2,
        "flowID": 4,
        "fileID": 2,
        "type": "partner",
        "page": 1,
        "positionX": 160,
        "positionY": 241,
        "sizeWidth": 150,
        "sizeHeight": 250
    }
]

Get the request body and make it array:

$rawPostBody = file_get_contents('php://input');
$signatures = (array)json_decode($rawPostBody);

Loop over the array:

foreach($signatures as $signature) {
    echo $signature->type;
}

Hope this helps those who ever look for how to do it.

Related