Come si passa un array all'API

In alcune chiamate API, è previsto l’invio di un array di valori nei dati POST. Come si fa?

Ho scoperto per tentativi ed errori come passare un array con un solo elemento: ad esempio, per change-owner, dovresti avere qualcosa come:

username: sean-finnegan
post_ids[]: 925

(o, in formato URL-encoded)

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

Ottima domanda, concordo che possa essere un po’ confuso. Se vuoi passare più post_ids, dovresti inserire più campi dei dati del modulo per post_ids[] come in questo esempio con curl:

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"

Ciao Blake,

è ancora questo il metodo consigliato per inviare un array all’API? Sto cercando di creare un webhook e non riesco a inviare il parametro array web_hook_event_type_ids.

Ho provato con CURL (come 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"

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

E con httpie (come 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]'

# Ottengo
{
    "errors": [
        "Web hook event types can't be blank"
    ]
}

Sembra che questo intero endpoint richieda i valori in un parametro web_hook nidificato:

Non sono molto favorevole a questo formato nidificato e ci sono diversi endpoint come questo nella mia lista futura da correggere. Puoi effettuare una chiamata API ad esso utilizzando form-data in questo modo:

Notate come ogni parametro abbia la sintassi “array” web_hook[payload_url]. Se invii la tua richiesta con JSON, apparirà così:

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

Ah, grazie mille. Non era quello che diceva l’API di Discourse, quindi stavo andando in tilt. :sweat_smile:

Inoltre, ho notato che impostare web_hook_event_type_ids con almeno un elemento è obbligatorio, anche se alla fine uso wildcard_web_hook=true. Anche questo mi ha fatto grattar la testa per un po’.