GraphQL
A new way to design APIs. Tired of mapping API data to get exactly the desired structure without any fuff!? GraphQL might be the answer.
Thanks to Meta (or facebook back then) to introducing this specification of designing APIs, it’s already a proven workhorse in the industry. Companies like Meta, Netflix and Airbnb have already adopted this technology.
GraphQL is an open-source data query and manipulation language for APIs and a query runtime engine.
There are many implementations of this specification in different languages, which you can find here. In this write we’ll specifically look into GraphQL features using Java via Springboot starter for GraphQL.
To begin, first we’ll start by defining our schema in schema.graphqls
file under src/main/resources/graphql/
directory.
type Query {
ads: [Ad]
ad(id: ID!): Ad
}
type Mutation {
createAd(adInput: AdInput): Ad
}
input AdInput {
title: String!
content: String
images: [Image]
status: AdStatus!
}
type Ad {
id: ID!
title: String!
content: String
images: [Image]
status: AdStatus!
}
type Image {
url: String!
alt: String
}
enum AdStatus {
PUBLISHED,
DRAFT
}
The two basic types in graphql are Query
and Mutation
.
Next, define your controller to handle the queries and mutations.
@Controller
public class AdController {
@QueryMapping
public Iterable<Ad> findAllAds() {
// ...
return ad;
}
@QueryMapping
public Optional<Ad> findAdById(@Argument Long id) {
// ...
return ad;
}
@MutationMapping
public Ad createAd(@Argument AdInput adInput) {
// ...
return ad;
}
}