Skip to content

Handling A Response

John Hutcheson edited this page Jun 15, 2020 · 8 revisions

Handling A Response From MailChimp

This library acts as a go between for your program and MailChimp's API, it acts in order to make understanding and using MailChimps API more simple. One way it does this is by providing ways to interface with the responses you get from the MailChimp API. When MailChimp responds to a request this library parses that response and populates an instance of a MailchimpResponse object. This class allows you to act on a requests response by giving you a set of getters and setters for each part of the response received from MailChimp. Lets say we made a get request against the root endpoint of the MailChimp API like this:

$response = $mailchimp->account()->get();

The MailChimp API documentation states that we should see a response similar to this:

HTTP/1.1 200 OK
Server: nginx
Content-Type: application/json; charset=utf-8
Content-Length: 2340
Vary: Accept-Encoding
X-Request-Id: bca135bf-860c-4614-a07b-a70b062680c0
Link: <https://api.mailchimp.com/schema/3.0/Root.json>; rel="describedBy"
Date: Tue, 15 Sep 2015 15:13:50 GMT
Connection: keep-alive


{
  "account_id": "8d3a3db4d97663a9074efcc16",
  "account_name": "Freddie's Jokes",
  "email": "[email protected]",
  "role": "owner",
  "contact": {
    "company": "Freddie's Jokes",
    "addr1": "675 Ponce De Leon Ave NE",
    "addr2": "Suite 5000",
    "city": "Atlanta",
    "state": "GA",
    "zip": "30308",
    "country": "US"
  },
  "last_login": "2015-09-15 14:25:37",
  "total_subscribers": 413,
  "_links": [...]
}

However this library will receive this response and break it down into a much more digestible instance of a MailchimpResponse. So what can we do with our response? Here are a list of methods we can use to derive information from our response object:

$response->getHeaders() // returns a map of the headers received with the response
$response->getHttpCode() // returns the HTTP code sent with the response
$response->getBody() // returns the response body as a string
$response->wasSuccess() // returns true if the http code is in the 200 range
$response->wasFailure() // returns true if the http code was outside of the 200 range

If we want to be able to reach into the response body and act on its contents in PHP, we will need to deserialize its contents. This can be achieved by calling the following on our response:

$account = $response->deserialize();

We can now reach into our response using PHP arrow operator. So if I wanted the account id for this account I can now call:

$id = $account->account_id;

Alternatively the deserialize() method takes an argument to deserialize your MailChimp response to arrays. This is done by calling deserialize(true). Should you choose this option you would then reach into your response like this:

$id = $account["account_id"];
Clone this wiki locally