verbb / consume

A Craft CMS plugin to create HTTP requests in your Twig templates to consume JSON, XML or CSV content.
Other
4 stars 1 forks source link

Getting full response? #10

Open bleepsandblops opened 6 months ago

bleepsandblops commented 6 months ago

Question

Hello, is there a way to get the full guzzle response, for example if I run this query $data = Consume::$plugin->getService()->fetchData('fedexTradeUpload', 'POST', 'documents/v1/etds/upload', $payload); $data returns null but if I drill down into Guzzle i manage to get this:

Screenshot 2024-01-24 at 16 48 19

by adding a debug on $response->getBody()->getContents() on this line https://github.com/guzzle/guzzle/blob/2779e868a00289e1b1fd854af030c43a06f4bcb4/src/Exception/RequestException.php#L112 So it's useful info I want to get somehow but it's not getting back all the way up the chain.

Thank you!

Additional context

No response

engram-design commented 6 months ago

There's two types of errors we handle with Consume. First is when the HTTP request reports back a non-2xx request. We then return the error as determined by Guzzle and other HTTP code/message.

The second case is when it's returned a 200 HTTP request (it succeeded technically), but there was an error in the API processing. This is the tricky one, as every API handles internal errors differently.

Now the reason that a fetchData() request returns null when there's an error is to allow handling in your templates on what to do when there's no data. If you executed this call in your templates, and there's an error, you can do:

{% set data = consume('fedex', 'POST', 'documents/v1/etds/upload') %}

{% if data %}
   // ...

I suppose we could change that to add an error property if there was an error, but that'd be a breaking change and would probably trip up a few people who would expect certain values to be present if the above data exists.

I've added a new option you can pass into a payload, which Consume will check to determine if you actually want the error response. This will be returned in an error key.

{% set data = consume('fedex', 'POST', 'invalid/endpoint', {
    includeErrorResponse: true,
}) %}

If this instance, you'll get:

[
  "error" => [
    "transactionId" => "b98c9467-934d-4c43-972c-a71df0c6ca9d"
    "errors" => [
      [
        "code" => "NOT.FOUND.ERROR"
        "message" => "The resource you requested is no longer available. Please modify your request and try again."
      ]
    ]
  ]
]

So you'll be able to check for if (data and not data.error).

bleepsandblops commented 6 months ago

@engram-design thanks so much for the explanation and the fix, looks perfect!