Thanks for the code. It’s hard to debug it fully without seeing all of the code. I would recommend querying the API outside of the script itself. For example, you could use curl
curl -X GET "https://mydiscourse.com/posts.json" \
-H "Api-Key: 714552c6148e1617aeab526d0606184b94a80ec048fc09894ff1a72b740c5f19" \
-H "Api-Username: michael"
If you’re not comfortable with the command line or using curl, I would recommend using Postman to debug the issue with the API. Postman is essential for me as a developer when testing or building APIs.
Here is a Postman workspace with Discourse routes already setup. Just configure your API key and username.
Discourse API Documentation Postman API Network