Introduction to Fetching API in Bricks

Schermata 2022-11-16 alle 10.10.24

In this tutorial, we’ll create a dynamic Chuck Norris quote picked from a public API to understand the basics of API fetching in Bricks.

Table of Contents

Create a custom function

Let’s open the functions.php file of our child theme and create a function called get_random_chuck_norris_quote and return some dummy text:

function get_random_chuck_norris_quote(){
   return 'This function works';
}

Now let’s open the Bricks builder, and paste the function inside our desired element using the bricks echo function. In this example, I’m using a Testimonial element:

Let’s check if everything is working on the frontend:

The function is working! Let’s connect the API!

Get the API response

First of all, let’s save the URL where the API is hosted inside a variable $random_url_api. Checking the https://api.chucknorris.io/ website, they clearly point to the following random API URL: https://api.chucknorris.io/jokes/random.

Now we need to perform an HTTP request using the GET method and return its response inside a new variable $response. We’ll use the wp_safe_remote_get() function to do that and will var_dump the $response variable to check what is being returned from the API:

function get_random_chuck_norris_quote(){

  $random_url_api = 'https://api.chucknorris.io/jokes/random';
  $response = wp_safe_remote_get($random_url_api);

  // Stop the function if the response returns an error
  if ( is_wp_error( $response ) ) {
	return false;
  }

  // Let's check the response content
  var_dump($response);

}

Now let’s check the frontend, you should see the following output:

Array
(
    [headers] => Requests_Utility_CaseInsensitiveDictionary Object
        (
            [data:protected] => Array
                (
                    [date] => Wed, 16 Nov 2022 09:21:15 GMT
                    [content-type] => application/json;charset=UTF-8
                    [via] => 1.1 vegur
                    [cf-cache-status] => DYNAMIC
                    [report-to] => {"endpoints":[{"url":"https:\/\/a.nel.cloudflare.com\/report\/v3?s=73SiirMj%2Btof7vtFw22wSz0zX%2FIf4zi5%2F05XDrR9mADuLd3CboRtOC2jn2r%2FRvHXPly1lNPh3r8%2BTvTf9SdtuIQHtMTj4oC0CDt2bP1J7sYs%2FRLkOizhLZRB1VaNfVsGJkubEuSQWZ2OHly%2FUv86gXg%3D"}],"group":"cf-nel","max_age":604800}
                    [nel] => {"success_fraction":0,"report_to":"cf-nel","max_age":604800}
                    [server] => cloudflare
                    [cf-ray] => 76af27c9ba2759fb-MXP
                    [content-encoding] => gzip
                    [alt-svc] => h3=":443"; ma=86400, h3-29=":443"; ma=86400
                )

        )

    [body] => {"categories":[],"created_at":"2020-01-05 13:42:23.880601","icon_url":"https://assets.chucknorris.host/img/avatar/chuck-norris.png","id":"psoHkcAVSWCD1cuXGRRveg","updated_at":"2020-01-05 13:42:23.880601","url":"https://api.chucknorris.io/jokes/psoHkcAVSWCD1cuXGRRveg","value":"Chuck Norris is ALL that AND a bag of chips!"}
    [response] => Array
        (
            [code] => 200
            [message] => OK
        )

    [cookies] => Array
        (
        )

    [filename] => 
    [http_response] => WP_HTTP_Requests_Response Object
        (
            [response:protected] => Requests_Response Object
                (
                    [body] => {"categories":[],"created_at":"2020-01-05 13:42:23.880601","icon_url":"https://assets.chucknorris.host/img/avatar/chuck-norris.png","id":"psoHkcAVSWCD1cuXGRRveg","updated_at":"2020-01-05 13:42:23.880601","url":"https://api.chucknorris.io/jokes/psoHkcAVSWCD1cuXGRRveg","value":"Chuck Norris is ALL that AND a bag of chips!"}
                    [raw] => HTTP/1.1 200 OK
Date: Wed, 16 Nov 2022 09:21:15 GMT
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Connection: close
Via: 1.1 vegur
CF-Cache-Status: DYNAMIC
Report-To: {"endpoints":[{"url":"https:\/\/a.nel.cloudflare.com\/report\/v3?s=73SiirMj%2Btof7vtFw22wSz0zX%2FIf4zi5%2F05XDrR9mADuLd3CboRtOC2jn2r%2FRvHXPly1lNPh3r8%2BTvTf9SdtuIQHtMTj4oC0CDt2bP1J7sYs%2FRLkOizhLZRB1VaNfVsGJkubEuSQWZ2OHly%2FUv86gXg%3D"}],"group":"cf-nel","max_age":604800}
NEL: {"success_fraction":0,"report_to":"cf-nel","max_age":604800}
Server: cloudflare
CF-RAY: 76af27c9ba2759fb-MXP
Content-Encoding: gzip
alt-svc: h3=":443"; ma=86400, h3-29=":443"; ma=86400

{"categories":[],"created_at":"2020-01-05 13:42:23.880601","icon_url":"https://assets.chucknorris.host/img/avatar/chuck-norris.png","id":"psoHkcAVSWCD1cuXGRRveg","updated_at":"2020-01-05 13:42:23.880601","url":"https://api.chucknorris.io/jokes/psoHkcAVSWCD1cuXGRRveg","value":"Chuck Norris is ALL that AND a bag of chips!"}
                    [headers] => Requests_Response_Headers Object
                        (
                            [data:protected] => Array
                                (
                                    [date] => Array
                                        (
                                            [0] => Wed, 16 Nov 2022 09:21:15 GMT
                                        )

                                    [content-type] => Array
                                        (
                                            [0] => application/json;charset=UTF-8
                                        )

                                    [via] => Array
                                        (
                                            [0] => 1.1 vegur
                                        )

                                    [cf-cache-status] => Array
                                        (
                                            [0] => DYNAMIC
                                        )

                                    [report-to] => Array
                                        (
                                            [0] => {"endpoints":[{"url":"https:\/\/a.nel.cloudflare.com\/report\/v3?s=73SiirMj%2Btof7vtFw22wSz0zX%2FIf4zi5%2F05XDrR9mADuLd3CboRtOC2jn2r%2FRvHXPly1lNPh3r8%2BTvTf9SdtuIQHtMTj4oC0CDt2bP1J7sYs%2FRLkOizhLZRB1VaNfVsGJkubEuSQWZ2OHly%2FUv86gXg%3D"}],"group":"cf-nel","max_age":604800}
                                        )

                                    [nel] => Array
                                        (
                                            [0] => {"success_fraction":0,"report_to":"cf-nel","max_age":604800}
                                        )

                                    [server] => Array
                                        (
                                            [0] => cloudflare
                                        )

                                    [cf-ray] => Array
                                        (
                                            [0] => 76af27c9ba2759fb-MXP
                                        )

                                    [content-encoding] => Array
                                        (
                                            [0] => gzip
                                        )

                                    [alt-svc] => Array
                                        (
                                            [0] => h3=":443"; ma=86400, h3-29=":443"; ma=86400
                                        )

                                )

                        )

                    [status_code] => 200
                    [protocol_version] => 1.1
                    [success] => 1
                    [redirects] => 0
                    [url] => https://api.chucknorris.io/jokes/random
                    [history] => Array
                        (
                        )

                    [cookies] => Requests_Cookie_Jar Object
                        (
                            [cookies:protected] => Array
                                (
                                )

                        )

                )

            [filename:protected] => 
            [data] => 
            [headers] => 
            [status] => 
        )

)

As you can see, it returns an array with a bunch of information we don’t need. In our case, we just need the quoted text which is located in [body].

To get the body part only, let’s use a really handy function: wp_remote_retrieve_body();

So let’s var_dump the body part only:

function get_random_chuck_norris_quote(){

  $random_url_api = 'https://api.chucknorris.io/jokes/random';
  $response = wp_safe_remote_get($random_url_api);

  // Stop the function if the response returns an error
  if ( is_wp_error( $response ) ) {
	return false;
  }

  // Get the body part
  $response_body = wp_remote_retrieve_body( $response );

  // Let's check the response body content
  var_dump($response_body);

}

The output is a JSON object that includes categories, id, url… and the value which is the data we’re looking for:

{
   "categories":[
      
   ],
   "created_at":"2020-01-05 13:42:26.447675",
   "icon_url":"https://assets.chucknorris.host/img/avatar/chuck-norris.png",
   "id":"wOgZCCWDReOnr3ws_Sqw2g",
   "updated_at":"2020-01-05 13:42:26.447675",
   "url":"https://api.chucknorris.io/jokes/wOgZCCWDReOnr3ws_Sqw2g",
   "value":"No matter how manly and hetro you claim to be, if you are given a nude photo of Chuck Norris, you will be dead from carpal tunnel syndrome within 4 hours."
}

Convert the JSON Object into a PHP array

We’re getting closer! We now return a JSON object that contains the quoted text as a value.

To extract the data from the JSON object, we need to use the json_decode() function and return a PHP array. Let’s var_dump the result:

function get_random_chuck_norris_quote(){

  $random_url_api = 'https://api.chucknorris.io/jokes/random';
  $response = wp_safe_remote_get($random_url_api);

  // Stop the function if the response returns an error
  if ( is_wp_error( $response ) ) {
	return false;
  }

  // Get the body part
  $response_body = wp_remote_retrieve_body( $response );

  // Decode the JSON object into a PHP array
  $response_body_decoded = json_decode( $response_body, true );

  // Let's check the response body content
  var_dump($response_body_decoded);

}

which output the following array:

Array
(
    [categories] => Array
        (
        )

    [created_at] => 2020-01-05 13:42:28.984661
    [icon_url] => https://assets.chucknorris.host/img/avatar/chuck-norris.png
    [id] => nYj4tJQ-T4ioHrzbr8rFMg
    [updated_at] => 2020-01-05 13:42:28.984661
    [url] => https://api.chucknorris.io/jokes/nYj4tJQ-T4ioHrzbr8rFMg
    [value] => By the time you see Chuck Norris in your rearview mirror, he's already kicked you in the face and is 10 car lengths ahead of you.
)

Return the desired value

Almost done! We now need to pick the value from the array and return it inside our function:

function get_random_chuck_norris_quote(){

  $random_url_api = 'https://api.chucknorris.io/jokes/random';
  $response = wp_safe_remote_get($random_url_api);

  // Stop the function if the response returns an error
  if ( is_wp_error( $response ) ) {
	return false;
  }
  
  // Get the body part 
  $response_body = wp_remote_retrieve_body( $response );

  // Decode the JSON object into a PHP array
  $response_body_decoded = json_decode( $response_body, true );

  // Return the quoted text
  return $response_body_decoded['value'];

}

And boom! Now we have successfully created a totally useless dynamic quote of Chuck Norris based on a public API! Congrats!

  • Maxime, this is really helpful, simple enough to understand the basics of communicating with an API, fetching JSON the response and converting it into PHP. Really, really useful. Thanks.

    One question: when you do the var_dump, where do you see the result with all that info, in the front end?

    • Thanks Aarón for the kinds words.
      Yes, var_dump($variable) will output the $variable content on the frontend. It’s usually used for debugging purposes, so be careful when using it on productions sites 😉

Leave your comment