Quick Summary
I'm building a search micro-service that will allow searching across different types of resources in a particular system (e.g. blog posts, users etc.). The API that will be exposed will be consumed by both web applications and native mobile applications.
My Solution
What I'm considering is returning an array of generic "SearchResult" objects. For example:
"results": [
{
"title": "My Blog Post",
"description": "My blog post description",
"image": "https://img.com/icon.jpg"
"link": "https://link.com"
"type": "blog-post"
},
{
"title": "Henry Jacobson",
"description": "Henry was born in a small village.",
"image": "https://img.com/henry.jpg"
"link": "https://link.com/henry",
"type": "user"
}
]
I think this is pretty flexible because it means that regardless of the type of resource that has been found, it'll be possible to parse it as a generic SearchResult object on the client side. This means we can return new resources in the future without having to worry about how any particular client will go about parsing them.
Sometimes, additional data might need to be provided in order to allow clients to do some custom rendering. I think this might be a good way of achieving that:
"results": [
{
"title": "My Blog Post",
"description": "My blog post description",
"image": "https://img.com/icon.jpg",
"link": "https://link.com",
"type": "blog-post",
"extra": {
"category": "Finance",
"commentCount": "501"
}
},
{
"title": "Henry Jacobson",
"description": "Henry was born in a small village.",
"image": "https://img.com/henry.jpg",
"link": "https://link.com/henry",
"type": "user",
"extra": {
"status": "active",
"topFriends": ["Jerry", "Jamie"]
}
}
]
Is there anything seriously flawed with this approach and if there is, what might be a better alternative?