Home > OS >  Is any way can we create generic API in GraphQL?
Is any way can we create generic API in GraphQL?

Time:08-30

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

CodePudding user response:

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
}
  • Related