Getting Started With Spring GraphQL
Sometimes the job description forces us into a scenario where the request param (or query params) are not always needed or required. The obvious way to get the job done is to check simply if the param is null or not. Let's try this and another smarter way using Optionals which come with Java since its version 8.


This article is the first step towards using GraphQL inside a Spring application.
But first, let's know more about GraphQL. According to Red Hat, GraphQL is a query language and server-side runtime for application programming interfaces (APIs) that focuses on providing clients with only the information they need.
GraphQL was created with the goal of making APIs that are quick, versatile, and developer-friendly. It may even be used within the GraphiQL integrated development environment (IDE). GraphQL, a REST alternative, allows developers to create queries that pull data from various sources in a single API call.
Additionally, GraphQL allows API administrators to add or remove fields without affecting existing queries. Developers may use any techniques they choose to create APIs, and the GraphQL definition will ensure that they work consistently for clients.
The project idea
The project we'll be building is a simple school/student find all endpoint — only this time using GraphQL which allows us to change and mutate our response data structure.
The student will have an id, name, email, and school, each school has an id and a name.
The student entity
The student repository
The school entity
The school repository
Now we created our controllers for the student and for the school with a simple findAll endpoint, starting with the student's:
The school controller will be similar to the student's:

Written by
Saad Elattar
Software engineer passionate about building scalable systems, exploring new technologies, and sharing knowledge through writing.
Get in touchKeep reading
Java 27 Is Here! What's New?
Java 27 ships 9 JEPs across security, language design, performance, and libraries. From post-quantum encryption to compact object headers, here's every feature explained with code examples and analogies.
A gentle introduction to eBPF: Zero-Code Observability for Java
What if you could get full distributed tracing on a plain Java HTTP server without adding any SDK, agent, or instrumentation code? This article walks through using Grafana Beyla and eBPF to automatically capture OpenTelemetry traces from a pure Java application, exporting them straight to Jaeger.




