Issue
I need to create generic api in graphql using spring boot e.g if getAll query returns model class but when in getAll query I sent parameter string which is model class name and it should return the result of that model class. grapgql file is as below
type Query{
getAll(clazz : String) : [User]
getOne(id : ID, clazz : String) : User
}
So instead of [User]
it should be something which is generic and hold relevant entity result.
Thanks in advance
Solution
GraphQL schema requires you to declare all fields that can be returned from the API, therefore building a generic API that can return any kind of data is not possible.
One option you have is to define properties of all possible Model types as fragments. Here's an example of a query that can return objects of type Character
, Jedi
, or Droid
:
query AllCharacters {
all_characters {
... on Character {
name
}
... on Jedi {
side
}
... on Droid {
model
}
}
}
Please find some more details here.
If you want to build an API that can truly return anything, you'll have is to serialise returned object to JSON (or any other string format) and return it as a string:
type Query{
getAll(clazz : String) : [String]
getOne(id : ID, clazz : String) : String
}
Answered By - jedrzej.kurylo
Answer Checked By - David Marino (JavaFixing Volunteer)