Home > Net >  Difficulty to understand PHP POST to REST API - mixed array and objects
Difficulty to understand PHP POST to REST API - mixed array and objects

Time:10-28

I'm trying to POST data to a REST API.

On Postman I can POST with success, the JSON body is:

{
  "version": 0,
  "roles": {
    "customer": {
    }
  },
  "person": {
     "firstName": "Inge",
     "lastName": "Musterfrau"
  },
  "emailAddresses" :{
    "private" : [
      "[email protected]"
    ]
  },
"addresses": {
    "billing": [
      {
        "supplement": null,
        "street": "aaa",
        "zip": "12345",
        "city": "Berlin",
        "countryCode": "DE"
      }
    ]
  }
        
}

My problem is on addresses billing. I don't know how to create the object/array correctly so the API accept it.

I'm build the parameters on PHO like bellow:

$billingAddr = array(
                    "supplement" => $billingAddress["streetDetails"],
                    "street" => $billingAddress["street"],
                    "zip" => $billingAddress["zipCode"],
                    "city" => $billingAddress["city"],
                    "countryCode" => $billingAddress["country"],
                );
                $params = [
                    "version"       => 0,
                    "roles"         => $roles,
                    "person"        => $person,
                    "emailAddresses"  => $emailAddresses,
                    "addresses"     => [
                        "billing"  => $billingAddr
                    ]
                ];

I get an error: "missing_entity - addresses - validation_failure".

I believe my issue is creating the mixed Object addresses, array billing.

CodePudding user response:

So, going strictly by the PHP example, doing a json_encode'd output of that shows that the structure is not quite the same at the addresses.

Note that I do not have the data for most of the rest of the json info from the PHP example, so the output examples below are strictly focused on the addresses section.

Before JSON change:

echo json_encode($params, JSON_PRETTY_PRINT);

{
    "version": 0,
    "roles": null,
    "person": null,
    "emailAddresses": null,
    "addresses": {
        "billing": {
            "supplement": null,
            "street": null,
            "zip": null,
            "city": null,
            "countryCode": null
        }
    }
}

... in that, note that the billing does not have the [] characters like what is sent using postman.

No worries though, it's an easy fix. The addresses part should be changed to get an array of billing addresses, like so:

"addresses"     => [
    "billing"  => [$billingAddr]
]

Then running a recheck with that change applied shows:

After JSON change:

echo json_encode($params, JSON_PRETTY_PRINT);

{
    "version": 0,
    "roles": null,
    "person": null,
    "emailAddresses": null,
    "addresses": {
        "billing": [
            {
                "supplement": null,
                "street": null,
                "zip": null,
                "city": null,
                "countryCode": null
            }
        ]
    }
}

That should help to achieve the expected format.

Here's the fiddle example in case you might need another PHP version to check. The fiddle default is 8.0.1

CodePudding user response:

Object properties and associative arrays are easy to access/declare directly; however, when you need to push data into indexed subarrays, you can to use [] syntax or array_push().

If you want to build a bit more maintainability in this code, you can build the variable-length subarrays as individual variables and then feed them into the master array just before json_encoding.

$version = 0;
$roles = ['customer' => []];
$person = [
    'firstName' => 'Inge',
    'lastName' => 'Musterfrau'
];
$emailAddresses = [
    'private' => [
        '[email protected]',
    ]
];
$billingAddresses[] = [
    'supplement' => $billingAddress["streetDetails"],
    'street' => $billingAddress["street"],
    'zip' => $billingAddress["zipCode"],
    'city' => $billingAddress["city"],
    'countryCode' => $billingAddress["country"]
];
// use $billingAddresses[] again to push another subarray into $billing

$data = [
    'version' => $version,
    'roles' => $roles,
    'person' => $person,
    'emailAddresses' => $emailAddresses,
    'addresses' => [
        'billing' => $billingAddresses
    ]
]

CodePudding user response:

This will create your array/json :

    $arr['version'] = "0";
    $arr['roles']['customer'] = [];
    $arr['person']['firstName'] = "Inge";
    $arr['person']['lastName'] = "Musterfrau";
    $arr['emailAddresses']['private'][] = "[email protected]";
    $arr['addresses']['billing'][0]['supplement'] = "";
    $arr['addresses']['billing'][0]['street'] = "aaa";
    $arr['addresses']['billing'][0]['zip'] = "12345";
    $arr['addresses']['billing'][0]['city'] = "Berlin";
    $arr['addresses']['billing'][0]['countryCode'] = "DE";
    
    $newJson = json_encode($arr);

Afterwards you json_encode it and voila the perfect json and very simple!

The best and easiest way to look at a json (to my opinion at least:) is as an array! (no shame in using the browser and echo "<pre>" here!) - We'll build an identical array and json it up back!

Once we see the json as an array we build the same in a very simple way here is the whole code example with step by step:

<?php

/*Our original json */
$json = '{
  "version": 0,
  "roles": {
    "customer": {
    }
  },
  "person": {
     "firstName": "Inge",
     "lastName": "Musterfrau"
  },
  "emailAddresses" :{
    "private" : [
      "[email protected]"
    ]
  },
"addresses": {
    "billing": [
      {
        "supplement": null,
        "street": "aaa",
        "zip": "12345",
        "city": "Berlin",
        "countryCode": "DE"
      }
    ]
  }

}';

$array = json_decode($json,true);
echo '<pre>';
/* original array */
echo "original array: ";
print_r($array);
echo '<pre>';
/* now lets create the same array with less fuss?! */

$arr['version'] = "0";
$arr['roles']['customer'] = [];
$arr['person']['firstName'] = "Inge";
$arr['person']['lastName'] = "Musterfrau";
$arr['emailAddresses']['private'][] = "[email protected]";
$arr['addresses']['billing'][0]['supplement'] = "";
$arr['addresses']['billing'][0]['street'] = "aaa";
$arr['addresses']['billing'][0]['zip'] = "12345";
$arr['addresses']['billing'][0]['city'] = "Berlin";
$arr['addresses']['billing'][0]['countryCode'] = "DE";

/* the new array: */
echo "our newly created array: ";
echo '<pre>';
print_r($arr);
echo '<pre>';
/* back to json */
echo "new Json: ";
echo '<pre>';
$newJson = json_encode($arr);
print_r($newJson);

This will return:

original array: Array
(
    [version] => 0
    [roles] => Array
        (
            [customer] => Array
                (
                )

        )

    [person] => Array
        (
            [firstName] => Inge
            [lastName] => Musterfrau
        )

    [emailAddresses] => Array
        (
            [private] => Array
                (
                    [0] => [email protected]
                )

        )

    [addresses] => Array
        (
            [billing] => Array
                (
                    [0] => Array
                        (
                            [supplement] => 
                            [street] => aaa
                            [zip] => 12345
                            [city] => Berlin
                            [countryCode] => DE
                        )

                )

        )

)
our newly created array: 
Array
(
    [version] => 0
    [roles] => Array
        (
            [customer] => Array
                (
                )

        )

    [person] => Array
        (
            [firstName] => Inge
            [lastName] => Musterfrau
        )

    [emailAddresses] => Array
        (
            [private] => Array
                (
                    [0] => [email protected]
                )

        )

    [addresses] => Array
        (
            [billing] => Array
                (
                    [0] => Array
                        (
                            [supplement] => 
                            [street] => aaa
                            [zip] => 12345
                            [city] => Berlin
                            [countryCode] => DE
                        )

                )

        )

)
new Json: 
{"version":"0","roles":{"customer":[]},"person":{"firstName":"Inge","lastName":"Musterfrau"},"emailAddresses":{"private":["[email protected]"]},"addresses":{"billing":[{"supplement":"","street":"aaa","zip":"12345","city":"Berlin","countryCode":"DE"}]}}

Building arrays can be very simple this way - almost feels linear! :)

  • Related