How to Use the icanhazdadjoke API in JavaScript

Are you looking for a way to spice up your website or app with a touch of humor? The icanhazdadjoke API is perfect for you! With a simple request, you can get a random dad joke to display wherever you'd like.

Getting started

Before beginning, make sure you have Node.js installed on your computer, since the following examples will be using the node-fetch library to make HTTP requests.

You don't need an API key to use the icanhazdadjoke API, so let's jump into some examples!

Example 1: Fetching a Random Joke

In this example, we'll use fetch() to make a GET request to the API and log the response to the console.

const fetch = require('node-fetch');

fetch('https://icanhazdadjoke.com/', {
    headers: {
        'Accept': 'application/json'
    }
})
    .then(response => response.json())
    .then(data => console.log(data.joke))
    .catch(error => console.error(error));

In the above code, we set the Accept header to application/json to indicate that we'd like to receive our response in JSON format. The response is then parsed with response.json() and logged to the console.

Example 2: Customizing the Joke Request

In this example, we'll use fetch() to make a GET request with some parameters to the API and display the joke in an HTML element.

const fetch = require('node-fetch');

const jokeElement = document.querySelector('#joke');

fetch('https://icanhazdadjoke.com/search', {
    method: 'GET',
    headers: {
        'Accept': 'application/json'
    },
    searchParams: {
        term: 'dad jokes',
        limit: 1
    }
})
    .then(response => response.json())
    .then(data => jokeElement.innerHTML = data.results[0].joke)
    .catch(error => console.error(error));

In this example, we make a GET request to the search endpoint with a term parameter of dad jokes and a limit parameter of 1, indicating that we only want one joke in our response. The response is then parsed and inserted into an HTML element with the innerHTML property.

Conclusion

In this short blog post, we went over how to use the icanhazdadjoke API in JavaScript. There are many other endpoints and parameters you can use to customize your joke requests, so be sure to check out the API documentation for more information.

Related APIs in Personality