How to accept a nullable Long in an API endpoint?

Viewed 121

Essentially, I have the following use case: I have an Entity, and need to update one of its fields. The field is a Long, and it CAN be null (basically, when I remove the entity I need to null out that field). We'll refer to this field as relativeId.

My React resource looks like this:

updateEntityField(entityId, relativeId) {
  return req({
    method: 'PUT',
    url: `stuff/entities/${entityId}/relative`,
    data: relativeId,
  });
},

And my Java resource look like this:

@ApiOperation("Updates an entity's relative id")
@PUT
@Path("/{id}/relative")
@Consumes(MediaType.APPLICATION_JSON)
public ApiResult<Arrest> updateRelativeId(
  @ApiParam(value = "Entity id", required = true) @PathParam("id") long entityId,
  @ApiParam(value = "relative id", required = true) @Nullable Long relativeId)
    {
        ...
    }

The relativeId is always null even if it's not null on the FE. I've never dealt with passing data that wasn't an object with multiple fields before, so I'm not sure what to do here. Ideally the relativeId can just be a path param, but it's difficult to pass null values through there. And I want to keep the resource simple, so I'm trying to avoid things like deliberately passing a -1, and then making that null when it's accepted in the BE.

1 Answers

You use the @QueryParam annotation, to read this optional value from request query param (also recommend updating the Swagger ApiParam to not be required):

@ApiParam(value = "relative id", required = false) @QueryParam @Nullable Long relativeId)

Then update the React code to pass it as a query param:

updateEntityField(entityId, relativeId) {
    return req({
        method: 'PUT',
        url: `stuff/entities/${entityId}/relative?relativeId=${relativeId}`
    });
},
Related