Creating and Adding Values to `custom_fields` via API

I am curious if there is any way to create and update Custom user fields (ie users >> custom_field) via the discourse API?

Accessing custon_fields - Discourse’s docs show how to access custom_fields via GET https://discourse.example.com/users/{username}.json..

Updating user_fields - This discussion “API: cannot update user” walks through how to use the API to PUT/update fields like name and user_fields (user fields created at admin/customize/user_fields).

But for the life of me, I cannot construct a working curl example in which custon_fields is created or updated.

For example,

curl -X "PUT" "https://{myDomain}/users/{username}.json?api_key=***&api_username=***" \
     -H "Content-Type: application/json" \
     -d $'{
  "custom_fields":{"test-val":"0.1"}
}`

Returns the following, which looks similar to a successful PUT (e.g. updating name or updating already-created user_fields).
However, custom_fields is not updated.

...
> Accept: application/json, text/xml, application/xml, */*
-> 
<- HTTP/1.1 200 OK
<- Server: nginx
<- Date: Mon, 30 Jul 2018 13:57:02 GMT
<- Content-Type: application/json; charset=utf-8
<- Transfer-Encoding: chunked
<- Connection: keep-alive
<- Vary: Accept-Encoding
<- X-Frame-Options: SAMEORIGIN
<- X-XSS-Protection: 1; mode=block
<- X-Content-Type-Options: nosniff
<- X-Download-Options: noopen
<- X-Permitted-Cross-Domain-Policies: none
<- Referrer-Policy: strict-origin-when-cross-origin
<- X-Discourse-Username: EconomiCurtis
<- X-Discourse-Route: users/show
<- Cache-Control: no-store, must-revalidate, private, max-age=0
....

This it tricky, the field needs to be whitelisted can you add it to /admin/customize/user_fields or is this field meant to be completely hidden from users?

2 Likes

The desired field would need to be completely hidden to users. (The current use-case is a set of user-specific statistics calculated outside of discourse - those metrics will be used to rank-order users listed on a groups page)

I realize user_fields has options for a field the user would only see once, upon sign-up. Is the best course of action to create a user_field and hide it on sign-up vis css?

Short of a plugin I think that is your only option here.

3 Likes

When updating the custom fields via the API, use the custom fields ‘number’ and not it’s name. If ‘test-val’ were the first field you created, the data line of your script would be:
-d '{ "user_fields": { "1": "0.1" } }'

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.