Response.ok with metadata

865 views Asked by At

In my RESTful service project I have method that add a record (new person):

In controller:

@PostMapping(value = "/addPerson")
public Response dodajOsobe(InputStream inputStream) {
    return osMgr.dodajOsobe(inputStream);
}

In Service:

public Response dodajOsobe(InputStream inputStream) {

    Response response = null;
    try {
        String input = misc.InputStreamToString(inputStream);
        Integer id = dodajOsobe(input);
        response = Response.ok("New person added").build();
    } catch (Exception e) {
        response = Response.serverError().entity("Nie udało się dodać osoby. Przyczyna: " + e.getLocalizedMessage()).build();
    }
    return response;
}

It returns object "Response" with status OK if everything is ok:

response = Response.ok("New person added").build();

After executing result in browser looks like this:

{
    "statusType": "OK",
    "entity": "New person added",
    "entityType": "java.lang.String",
    "metadata": {},
    "status": 200
}

I want to return the id of the person. I know that I can do this in "entity", but I want to have there redeable info. There is field "metadata" and I wont to put the id of record there, like this:

{
    "statusType": "OK",
    "entity": "New person added",
    "entityType": "java.lang.String",
    "metadata": {"id":112233},
    "status": 200
}

How to do that??

2

There are 2 answers

2
piradian On

You can create custom response class e.g.

class OkResponse {
  private EntityId id; //or something else
  private String message;
}

and return its instance as a response.

0
Olek On

I finally add header method:

        response = Response.ok("New record added")
                .header("rezerwacjaId", rezId)
                .build();

And got JSON:

{
  "entity": "New record added",
  "entityType": "java.lang.String",
  "metadata": {
    "rezerwacjaId": [
      77754
    ]
  },
  "status": 200,
  "statusType": "OK"
}