Running script to pull json from external API

Is there a way to use some logic to do more advanced requests to an external API? The API I want to pull data from requires a few steps to get to the data i want. Right now I’m using a bash script to handle that. Is there a way to either have hugo run that bash script (multiple scripts actually) or a way to have some javascript function that runs every X days to refresh the data?

You can do pretty much with GetRemote:

You say something about “a few steps” without detailing what those steps are, so I wouldn’t know.

1 Like

Does GetRemote handle parsing like jq? Does it have if logic? I’m calling an authenticated API and parsing out a values then making additional calls based on those values. Thats the high level steps. I see that GetRemote supports headers which takes care of authentication, but i need to be able to do more than a single request.

Can you use the result of one .GetRemote call (e.g., an access token) as input to another .GetRemote call?

Here’s an an example of getting a Spotify access token:

{{ $id := getenv "HUGO_SECRET_SPOTIFY_ID" | string }}
{{ $secret := getenv "HUGO_SECRET_SPOTIFY_SECRET" | string }}
{{ $auth := printf "%s %s" "Basic" (printf "%s:%s" $id $secret | base64Encode) }}

{{ $opts := dict
  "method" "post"
  "headers" (dict
    "Authorization" $auth
    "Content-Type" "application/x-www-form-urlencoded"
  "body" "grant_type=client_credentials"

{{ with resources.GetRemote "" $opts }}
  {{ with .Err }}
    {{ errorf "%s" . }}
  {{ else }}
    {{ $m := transform.Unmarshal . }}
    Access token = {{ $m.access_token }}<br>
    Expires in = {{ $m.expires_in }}<br>
    Token Type = {{ $m.token_type }}<br>
  {{ end }}
{{ else }}
  {{ errorf "Unable to obtain access token" }}
{{ end }}

The transform.Unmarshal function wrangles the JSON result into a map — $m.

You could then use $m.access_token as input to the next call. You would probably want to nest the next call within the inner else, directly after $m is initialized.


Hi @mgriff

I think what you are looking for is an example of how api’s work and a theme or demo website that you can use or take inspiration from. If yes keep an eye on this post you will find all the helpful answers there.

you can also find more details in the Hugo docs


@jmooring this is exactly what i was looking for :exploding_head: thank you!

I’ve only been using hugo for a week and it’s mainly been using local json and a custom theme. All the examples for external json are single requests with no logic around them like the example you provided. This will allow me to add a bunch of functionality. thanks again!!

1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.