REST API Calls In Julia

How To Make REST API Calls In Julia

In this tutorial, you’ll learn how to make REST API calls in Julia. Assuming you have Julia installed and running in your system. let’s get started.

Install The HTTP Package

For installing and managing packages in Julia, you have a Julia package manager. Assuming you are familiar with installing packages in Julia, from the terminal navigate to the Julia prompt.

ajay@ajay-HP-Notebook:~$ julia
               _
   _       _ _(_)_     |  Documentation: https://docs.julialang.org
  (_)     | (_) (_)    |
   _ _   _| |_  __ _   |  Type "?" for help, "]?" for Pkg help.
  | | | | | | |/ _` |  |
  | | |_| | | | (_| |  |  Version 1.0.1 (2018-09-29)
 _/ |\__'_|_|_|\__'_|  |  Official https://julialang.org/ release
|__/                   |

julia>

Once you are inside the Julia prompt, install the HTTP package using Pkg.

julia> using Pkg

julia> Pkg.add("HTTP")
 Resolving package versions...
  Updating `~/.julia/environments/v1.0/Project.toml`
  [cd3eb016] + HTTP v0.7.1
  Updating `~/.julia/environments/v1.0/Manifest.toml`
  [cd3eb016] + HTTP v0.7.1
  [83e8ac13] + IniFile v0.5.0
  [739be429] + MbedTLS v0.6.4

Make REST API Calls In Julia

Once you have the HTTP package installed, create a file called app.jl. Import the HTTP package inside app.jl. Make use of the get method from HTTP library to make the API call.

using HTTP
function make_API_call(url)
    try
        response = HTTP.get(url)
        return String(response.body)
    catch e
        return "Error occurred : $e"
    end
end

response = make_API_call("http://jsonplaceholder.typicode.com/users")
println(response)

As seen in the code, you have defined a function called make_API_call which makes use of the HTTP Julia package to make the GET API call. Once the API call has been completed, the response is returned into a response object. response.body gives the API response.

Wrapping It Up

In this tutorial, you learnt about how to make REST API calls in Julia. You have made use of the HTTP package for calling the APIs. Have you used any other packages for calling the APIs from Julia ? Do let us know your thoughts in the comments below.