Updating relations using the REST API

As sometimes happens, it finally dawned on me to try custom controller call.

So - route is added:

{
    method: "PUT",
    path: "/service/storeService/:id",
    handler: "api::service.service.storeService",
  },

and in controller - this code saves the service successfully. Relation that I need is saved with just giving an ID of the related record.

async storeService(ctx) {
		try {
			const { id } = ctx.params
			const { data } = ctx.request.body

			await strapi.db.query('api::service.service').update({
				where: { id: id },
				data: data
			})

			ctx.body = {
				status: "ok"
			}
		} catch (err) {
			console.error(err)
			ctx.body = {
				status: "error"
			}
		}
	},

The front-end code that is using this is basically the same as for API call - just the URL link to this new method.

// finally, save the record
          res = await fetch(
            // STRAPI_URL + "/api/services/" + activeService.id,
            STRAPI_URL + "/api/service/storeService/" + activeService.id,
            {
              method: "PUT",
              headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer ' + props.auth.jwt
              },
              body: JSON.stringify({ data: activeRecord })
            }
          )

activeRecord is just a JSON object - as you would expect.

In order to get populated relation data - you do need to reload the record via normal API call.

I do need to test this like hell - just to be sure, but for now, this workaround is doing that API call was supposed to do.

Hopefully this helps you out - even though I really would prefer API calls to work as described :confused: