Discourse API Testing
Discourse is used for a number of purposes, but their forum software is quite popular. I’ve been looking at how to us the Discourse API to automate creating posts. This blog post describes how to setup a local Discourse instance and perform API calls against it.
Setup Discourse Container
This step is fairly straightforward thanks to Bitnami’s Discourse Docker container which launches and configures all the components in a Docker Compose environment.
At first I just tried to launch it with
docker compose up -d and while it
appeared to start and run successfully I couldn’t see anything in my browser. I
then read that you have to set the
DISCOURSE_HOSTNAME to the IP address you
want to run Discourse on. If you’re running on localhost, set it to
cleared it up for me.
So after editing the
docker-compose.yml file, it now looks like this, and is
ready to start Discourse:
Now run docker-compose, with the command:
Wait a minute for the application to come up and continue on to the next section. If you want to query the containers to verify they are all up, you’ll see 4 of them, similar to:
Create a Discourse User
For this test, I don’t need to setup SMTP email because I’m really only trying out the Discourse API locally. Unfortunately Discourse relies on SMTP to send emails for every user registration, even the first user signup process. For our purposes, we don’t need email capability, we only need a user to login and create an API token.
This can be accomplished using the following steps.
Connect to the discourse container:
[user@host bitnami-docker-discourse]$ docker exec -it bitnami-docker-discourse_discourse_1 /bin/shell
Using the steps for “Need to log in without receiving a registration email?” in the email troubleshooting documentation as a guide, we’ll run
raketo create an admin account:
- Login to the Discourse GUI using the user/password you created above
Create API Key
Next we’ll create the API key that we’re going to use to create posts. Follow these steps:
- Go to the Admin page (hamburger menu in upper right)
- Click on the API tab at the top
- Select “New API Key”
- Plug in your username, the description, and the user level of “Single User”
Write down the key because you’ll never see it in full again if you forget it. (But of course you can create a new one and delete this one very easily.)
Create New Category
You can create a new category via the GUI, but to do this via the API use a command similar to:
The new category ID (as shown in the response,) is
Create a Post in the New Category
To finally perform the post creation using the API, do something like:
And now you’ve created a new post using the API. Mission accomplished! (For real, not like with W.)