galironfydar
1 week ago
123
5
General

Best way to comsume this API response

Posted 1 week ago by galironfydar

So, I have the following API response:

{
  "resourceType" : "Parameters",
  "parameter" : [
    {
      "name" : "read_receipt",
      "part" : [
        {
          "name" : "documentIdentifier",
          "valueString" : "1"
        },
        {
          "name" : "read",
          "valueBoolean" : true
        }
      ]
    },
    {
      "name" : "read_receipt",
      "part" : [
        {
          "name" : "documentIdentifier",
          "valueString" : "2"
        },
        {
          "name" : "read",
          "valueBoolean" : false
        }
      ]
    }
  ]
}

I'm interested in the "read" column for a given id. I JSON decode the response and loop through the parameter currently.

$values = [];
foreach ($response->parameter as $parameter) {
    $part = $parameter->part;
    $values[$part[0]->valueString] = $part[1]->valueBoolean;
}

This is my solution to get the ID => readValue. But this seems super messy. There much be a better way? I suppose the part array indexes could also change as well, I have no control over what gets returned from the API. So I would need a way to get the read value from a documentIdentifier ID.

I'm not actually using Laravel for this project, so I'm trying to do this without reaching for collections. Am, I wasting my time. Is processing the response the only way to achieve this?

Please sign in or create an account to participate in this conversation.