To get around the limitations described, Facebook developed a new way of doing APIs called GraphQL. It is an API whose style is more compatible with database query constructs, with schemas for different types and a runtime for executing queries and mutations.
GraphQL uses the Schema Definition Language (SDL) to define the schema of various types in the API, as follows:
type Hotel { id: String! displayName: String! city: String ! noRooms: Int starRating: Int }
This is the schema for a hotel. It has four fields: id, displayName, noRooms, and starRating, each with a description of its primitive type. The ! symbol indicates that the field is mandatory.
It is also possible to describe relationships between types. So we can have HotelChain, which has a set of hotels:
type HotelChain { name: String! hotels: [Hotel!]! }
Here the square bracket indicate an array.
Note that github.com/graphql-go/graphql provides support for graphql in Golang. The following code snippet shows how to define a Golang struct and an equivalent type in graphql:
type Hotel struct { Id string `json:"id"` DisplayName string `json:"displayName"` City string `json:"city"` NoRooms int `json:"noRooms"` StarRating int `json:"starRating"` }
// define custom GraphQL ObjectType `hotelType` for our Golang struct `Hotel` // Note that // - the fields map with the json tags for the fields in our struct // - the field types match the field type in our struct var hotelType = graphql.NewObject(graphql.ObjectConfig{ Name: "Hotel", Fields: graphql.Fields{ "id": &graphql.Field{ Type: graphql.String, }, "displayName": &graphql.Field{ Type: graphql.String, }, "city": &graphql.Field{ Type: graphql.String, }, "noRooms": &graphql.Field{ Type: graphql.Int, }, "starRating": &graphql.Field{ Type: graphql.Int, }, }, })
Once we have the types, we can then define a schema, with root query and mutation structures:
// define schema, with our rootQuery and rootMutation var schema, schemaErr = graphql.NewSchema(graphql.SchemaConfig{ Query: rootQuery, Mutation: rootMutation, })
We shall see more details on the rootQuery and rootMutation structures later. This now defines the complete schema needed.