如何将数组传递给 api

On some of the api calls, you are expected to pass an array of values in the post data. How do you do this?

I have figured out by trial an error how to pass an array with one item in it - e.g. for change-owner, you want something like:

username: sean-finnegan
post_ids[]: 925

(or, in url-encoded)

post_ids%5B%5D=925&username=sean-finnegan
2 个赞

Great question, I agree that can be a bit confusing. If you want to pass multiple post_ids you would pass in multiple form data fields for post_ids[] like this curl example:

curl -i -sS -X POST "http://localhost:8080/t/15/change-owner.json" 
-H "Api-Key: api-key" \
-H "Api-Username: system" \
-F "username=blake" \
-F "post_ids[]=29" \
-F "post_ids[]=30"
5 个赞

Hey Blake,

Is this still the recommended way to send an array to the API? I’m trying to create a web hook and I’m not able to send the web_hook_event_type_ids array parameter.

I’ve tried it with CURL (as multipart/form-data)

curl -X POST "https://MYSITE.com/admin/api/web_hooks" \
  -H "Api-Key: KEY" \
  -H "Api-Username: USER" \
  -F "payload_url=https://MYOTHERSITE.com" \
  -F "content_type=1" \
  -F "wildcard_web_hook=false" \
  -F "verify_certificate=true" \
  -F "active=true" \
  -F "web_hook_event_type_ids[]=2"

# I get
{"errors":["param is missing or the value is empty: web_hook"]}%

And with httpie (as application/json):

http POST https://MYSITE.com/admin/api/web_hooks \
  Api-Key:KEY \
  Api-Username:USER \
  payload_url=https://MYOTHERSITE.com \
  content_type=1 \
  wildcard_web_hook:=false \
  verify_certificate:=true \
  active:=true \
  web_hook_event_type_ids:='[2]'

# I get
{
    "errors": [
        "Web hook event types can't be blank"
    ]
}
1 个赞

Looks like this whole endpoint wants the values in a nested web_hook param:

I’m not a huge fan of this nested format, and there are a few endpoints like this that are on my eventual list to fix. You can make an API call to it using form-data like so:

image

Notice how each parameter has the “array” syntax web_hook[payload_url]. If you are sending your request with json it will look like:

{
  "web_hook": {
    "payload_url": "https://example.com/hello",
    "content_type": "1",
    ...
  }
} 
4 个赞

Ah, thank you so much. That’s not what it said in the Discourse API, so I was going crazy. :sweat_smile:

Also, I’ve noticed that setting web_hook_event_type_ids to at least one item is required even if I end up using wildcard_web_hook=true. That also had me scratching my head for a while.

1 个赞