How to grant a custom badge through the API


(Simon Cossar) #1

Custom badges that you have created on your forum can be granted through the API. This is a great way to award badges without having to use custom badge SQL.

To grant a badge through the API, you need to know the username of the user that you wish to grant the badge to, and the ID of the badge you wish to grant. You also need to make sure you have generated an All Users API Key from your site’s Admin/API section.

Finding your API Key

This screenshot is from my local development site. Generally, you need to be very careful about sharing your API keys:

Finding the Badge ID

You can get the Badge ID from the badge’s URL. Go to your Admin/Badges section and then click on the badge that you wish to grant. The URL will look something like this: https://forum.example.com/admin/badges/102. The last number in the URL is the badge ID.

Making the API call

To test an API call, you can try granting a badge using curl or Postman. Here is how I grant a badge from my computer’s terminal with curl.

First, to make things easier, set an api_key variable:

 api_key=yourallusersapikey

Then to grant a badge with the ID of 102 to the user simon.cossar:

curl -X POST -d "api_key=$api_key&api_username=system&badge_id=102&username=simon.cossar" https://forum.example.com/user_badges

You should get a JSON response with details about the badge and when it was granted.


(Caliph Khan (Caliph Khan)) #2

won’t it need a reason for granting the badge?
I have wrote a plugin for my wordpress site that grants user badges on product purchase. It was working fine for previous version of discourse but on new version it needs a valid forum post url in a reason to grant a badge. Can you confirm? or do I need to explain my situation more?


(Simon Cossar) #3

I am still able to grant custom badges with the API request that I gave in the initial post. With WordPress, you will be able to construct a similar query using wp_remote_post.

What is the response you get from Discourse when you try to grant the badge?


(Caliph Khan (Caliph Khan)) #4

I am using wp_remote_post

here is my code

$arr                   = array(
    
    'api_key' => $api_key,
    
    'api_username' => $api_username,
    
    'username' => $username,
    
    'badge_id' => $badge_id,
    
   // 'reason' => $reason
    
);
$create_badge_response = wp_remote_post($create_badge_url, array(
    
    'method' => 'POST',
    
    'body' => $arr
    
));

It was giving 422 response.
Previously I was using this phrase “Purchased product on website” as a reason which stopped working on the update after 2.2.0beta5

I just checked and removed the reason from the url and it worked fine.


(Simon Cossar) #5

I think you might have found a bug. When I try granting a badge through the UI and adding a reason, it’s returning a 400 error. If I don’t include a reason, I can grant the badge through the UI or the API without any problems.