Create topic using Discourse API

Hello
I need your help please.
I’m trying to create a topic using Discourse API but it’s fail every time I tried. This is my code :

https://myDiscourse.com/posts.json?title=New+test+posted&raw=new+posted+text+to+test+creation+by+api&category=45&api_key=xxxxxxxxxxxxxxxxxxxxxxxx&api_username=admin

I don’t know what is wrong, can you help me please?

Thanks

You can’t include the API key in the url (it exposes your key you anyone who can see your web traffic). They key must be passed in the headers.

See Grant a custom badge through the API for an example.

1 Like

Hello @pfaffman
Thank you for your help. I tried according to example but there is a error :

401 Authorization Required

My script :

$apikey = "xxxxxxxxxxxxxxxxxxxx";
	$username = "xxxxxxxxxxxxxxxxx";
	
	$title = "test";
	$raw = "message";
	$category = 9;
	
	$url = 'https://myDiscourse.com/posts.json';
	$post_fields = array(
		'title' => $title,
		'raw' => $raw,
		'category' => $category,
	);
	$headers = array("Content-Type: multipart/form-data;","Api-Key: $apikey","Api-Username: $username",);

	$ch = curl_init();
	curl_setopt( $ch, CURLOPT_URL, $url );
	curl_setopt( $ch, CURLOPT_POST, 1 );
	curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
	curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
	curl_setopt( $ch, CURLOPT_POSTFIELDS, http_build_query( $post_fields ) );
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

	$result = curl_exec( $ch );

	if ( curl_errno( $ch ) !== 0 ) {
		echo 'Error:' . curl_error($ch);
	}

	curl_close( $ch );

I made a mistake certainly but I don’t know what. Can you help me please?

Thanks

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

3 Likes