Authenticating using API keys when accessing API through fetch

Hey!

I’m building a headless WP site for a magazine which has their community on Discourse, and the comments are to be integrated on the article pages. I found the API docs and was super happy, as the iframe embed wasn’t really what I was looking for as the site will have dark & light mode, so I need the comments template to inherit CSS variables from the root element.

However I keep running into the rate limit when I try to access the API directly (using fetch on https://discourseurl.com/t/{id}.json), so I figured I’d try adding an API key and authenticating using it.

I’m using this code:

fetch(this.apiUrl, {
        headers: {
          'User-Api-Key': '{user api key from Discourse admin}',
        },
      })

and I get this error, no matter which key I use (even trying with an admin key):

error_type: "invalid_access"
errors: Array [ "Du har inte behörighet att visa den efterfrågade resursen." ]```

Rough translation: “You do not have access to the requested resource”.

Am I missing something in regards to how the API keys work? What would be the recommended approach to request these API endpoints without hitting the rate limit?

1 Like

Have a look at the Authentication section that’s near the top of https://docs.discourse.org/. It gives an example of how to set your API credentials in the request header. You need to use Api-Key and Api-Username in the header.

7 Likes

Thanks! Can’t imagine how I missed the auth part there, been looking through the docs over and over again :joy:

Anyway, I seem to be making some kind of progress, but I run into this issue now in the browser console:
(Reason: missing token ‘api-key’ in CORS header ‘Access-Control-Allow-Headers’ from CORS preflight channel).

I’m not sure what might be causing it, can’t find anything in the forum about it either. Am I missing something? Weird thing is that I am specifying the header as ‘Api-Key’ in my code. Any ideas? :slight_smile:

Sounds like you are building a JavaScript app and making the API requests from the browser?

The recommended approach would be to make the API calls to Discourse server side, and have your JavaScript app talk to your server just how it talks to WordPress. This way you avoid any CORS issues.

3 Likes

Ah, awesome! This made me look through the WP Discourse code and realize I’m just an option away from WP exposing the API endpoint I need (exposing the Discourse comments via an API). I’ll just have to tweak it a little bit. That’s excellent, thanks a bunch :slight_smile:

Just curious, why isn’t it recommended to work directly against the Discourse API from the client side? I have some ideas on expanding on the project later on if there will be any budget (with a login functionality, for example), and I would like it to talk with the Discourse API. Would I have to route everything through Wordpress? :slight_smile:

2 Likes