Looking for a reputed java library for Spring boot application, where, GET api which returns a list of resources quite huge in size. To reduce the size of the response, one of the conventions is to only have fields requested in response.
Example,
GET /v1/users/
{
"data" :
{
[
{
"name" : "User1",
"phone" : "800-999-9999",
"city" : "XYZ1",
"country" : "PQR1"
},
{
"name" : "User2",
"phone" : "800-999-9999",
"city" : "XYZ2",
"country" : "PQR2"
}
]
}
}
For lighter version of response, when fields are passed as query parameters
GET /v1/users/?fields=name,city
{
"data" :
{
[
{
"name" : "User1",
"city" : "XYZ1"
},
{
"name" : "User2",
"city" : "XYZ2"
}
]
}
}
To learn more “Teach a dog to REST“. Mentions some the practices at linkedIn, facebook, twilio, etc.
I came across “https://github.com/monitorjbl/json-view“. But was shot down by the team.
Does anyone know a open-source licensed project to this? How do organizations using java spring microservices implement this feature? Thanks!
2
Answers
This is one of the difficult things with API design. You need to find the right trade-off between making it generic enough to support several use-cases without adding information which is rarely needed. One possibility is to create another endpoint. However, this can lead to lots of endpoints and bad API design.
I don’t exactly know your use-case, but instead of REST, you can look into GraphQL. In GraphQL, the client basically tells the server what information it wants to receive.
Besides that, there are already a few posts on stackoverflow which may help:
One approach that might work (haven’t tried this) would be to use e.g. flexjson, and specify the fields to include in the response when calling JSONSerializer.serialize(), something like: