resources.GetRemote - Strapi API Response: Bad Request (400)

Dear Community,

I have just started working with Hugo and Strapi. Unfortunately, I have a problem here that I can’t get any further with. So please don’t be too hard on me.

When I test the post with Postman, I get the expected JSON return from Strapi and an HTTP status 200, so Graphql and Token are correct.

Unfortunately, the way I have implemented the request here in Hugo, I always get a bad request. Have I probably overlooked something obvious?

My Strapi installation is not running locally, but on a VPS. Perhaps this is relevant? But then the post via Postman should also fail?

{{ $url := "http://strapi-url.tld:1337/graphql" }} 

{{ $opts := dict 
    "method" "post"
    "headers" (dict
        "Authorization" "Bearer STRAPI-API-TOKEN"
        "Content-Type" "application/graphql"
    )
    "body" `query {
        home {
          data {
            attributes {
              title
            }
          }
        }
      }`
}}

{{ with resources.GetRemote $url $opts }}
  {{ with .Err }}
    {{ errorf "Unable to get remote resource: %s" . }}
  {{ else }}
    {{ .Content }}
  {{ end }}
{{ else }}
  {{ errorf "Unable to get remote resource: %s" $url }}
{{ end }}

Thanks!

Best,

Nils

Sometime, you can use %#v to print more information.

  {{ with .Err }}
    {{ errorf "Unable to get remote resource: %#v" . }}
  {{ else }}

A working code snippet.

  {{ $body := dict "query" `{
    article(id: 3) {
      data {
        id
        attributes {
          title
        }
      }
    }
  }` }}
  {{ $opts := dict 
      "method" "post"
      "headers" (dict
          "Authorization" "Bearer YOUR_TOKEN"
          "Content-Type" "application/json"
      )
      "body" (jsonify $body)
  }}

Key points

  1. The Content-Type was set as application/json.
  2. The body was transformed as a string by jsonify.

You need to tweak the body (query) to suit your case.

2 Likes

Dear razon,

thank you so much, you helped me a lot!

Best,

Nils

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