How To Perform a GET Request Using the Command-line Interface on macOS

Shell

Instead of making HTTP requests with software tools such as Postman, making requests via the command line can be a handy skill. On a Mac you can accomplish this using command-line tools like wget (World Wide Web get) and jq (a JSON processor for readable output). In this blog post we assume the API endpoint is setup to return JSON.

Step 1: Install Homebrew

Homebrew is a package manager for macOS that simplifies the installation of various software packages. You can install it by executing the following command in your terminal:

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

Step 2: Install wget and jq

Once Homebrew is installed, you can use it to install wget and jq by running:

brew install wget jq

Step 3: Performing the HTTP GET Request

With both of these tools installed, you are ready to make the following GET request:

wget -qO- https://rickandmortyapi.com/api | jq .

-q : Stands for "quiet". It suppresses output except for errors.

-O- : Specifies where to write the output from the downloaded file. Here, the last - means the output will be directed to standard output (STDOUT), which is typically the terminal window.

| : A pipe symbol which is used to pass the output of one command as input to another command, which in this case is jq. The . in jq . specifies that jq should pretty-print the JSON data received from wget.

By executing the above request you should get the following response, which is the actual body or payload:

{
  "characters": "https://rickandmortyapi.com/api/character",
  "locations": "https://rickandmortyapi.com/api/location",
  "episodes": "https://rickandmortyapi.com/api/episode"
}

If you would like to output the server response headers, add the -S option.

wget -qSO- https://rickandmortyapi.com/api | jq .

which should give you something like this:

HTTP/1.1 200 OK
  Access-Control-Allow-Origin: *
  Age: 20904
  Cache-Control: max-age=259200
  Cache-Status: "Netlify Edge"; hit
  Content-Length: 166
  Content-Type: application/json; charset=utf-8
  Date: Sun, 14 Apr 2024 13:39:45 GMT
  Etag: W/"a6-enZrapqif5C6f+1pGTVpl8IEmfQ"
  Expires: Wed, 17 Apr 2024 07:51:21 GMT
  Netlify-Vary: query
  Server: Netlify
  Strict-Transport-Security: max-age=31536000
  X-Nf-Request-Id: 01HVEDBNF7MTS4PF7KXRNTEV3Y
  X-Powered-By: Express
{
  "characters": "https://rickandmortyapi.com/api/character",
  "locations": "https://rickandmortyapi.com/api/location",
  "episodes": "https://rickandmortyapi.com/api/episode"
}

By following these steps, you can swiftly make HTTP GET requests from the command line on your Mac using wget and jq. This simple yet powerful technique can be invaluable in various development and troubleshooting scenarios. Happy coding!