API経由でトピックを更新する際に["BAD CSRF"]を取得しています[python]

みなさん、こんにちは。トピックの更新で問題が発生しています。最初の投稿の id は、こちら に示されているように取得できています。以下のコードを実行することで確認できます。

import requests
from requests.structures import CaseInsensitiveDict

url = "https://my/discourse/instance/posts/{post_id}.json"

headers = CaseInsensitiveDict()
headers["Authorization"] = "{\"api-key\": \"{le_api_key}\", \"api-username\": \"{le_username}\"}"

resp = requests.get(url, headers=headers)

print(resp.status_code)

これは 200 のステータスコードを返し、期待通りの投稿情報が取得できています。

しかし、以下のコードを実行しようとすると、

import requests
from requests.structures import CaseInsensitiveDict

url = "https://my/discourse/instance/posts/{post_id}.json"

headers = CaseInsensitiveDict()
headers["Authorization"] = "{\"api-key\": \"le_api_key\", \"api-username\": \"le_username\"}"
headers["Content-Type"] = "application/json"

data = """
{
  "post": {
      "raw": "Cool post, but here's an updated to the post's body",
      "edit_reason": "I changed this because I can."
   }
}
"""

resp = requests.put(url, headers=headers, data=data)

print(resp.status_code)

["BAD CSRF"] というエラーが返ってきます。

私は管理者権限を持っており、使用しているキーは global です。できれば、権限の少ないキーで実行したいと考えています。
この投稿は、API を介して作成したトピックの最初の、かつ唯一の投稿です。

どうぞよろしくお願いいたします。:slight_smile:

なぜ Authorization という辞書キーの下にヘッダーをネストしているのですか?Discourse REST API Documentation にはその記載がありませんね :thinking:

「いいね!」 2

おっしゃる通り、API テストに使用しているツールがその挙動をしており、実際に動作しています。これ自体が問題のようです:

header1 = CaseInsensitiveDict()
header1["Authorization"] = '{"api-key": "longapikey", "api-username": "myusername"}'

header2 = {"api-key": "longapikey", "api-username": "myusername"}

r = requests.get(url, headers= HEADER)

HEADERheader1 と等しい場合は動作しますが、header2 と等しい場合は以下のエラーが発生します:

{"errors":["リクエストされたリソースを表示する権限がありません。API ユーザー名またはキーが無効です。"],"error_type":"invalid_access"}

ちなみに、ご返信ありがとうございます!