<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Philippe Simo on Medium]]></title>
        <description><![CDATA[Stories by Philippe Simo on Medium]]></description>
        <link>https://medium.com/@philippechampion58?source=rss-dabec628e4fd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*GVk0UJ_avEli35CjVUWi_w.png</url>
            <title>Stories by Philippe Simo on Medium</title>
            <link>https://medium.com/@philippechampion58?source=rss-dabec628e4fd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 19:58:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@philippechampion58/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Testing your GraphQL APIs in a Spring-boot app]]></title>
            <link>https://medium.com/swlh/testing-your-graphql-apis-in-a-spring-boot-app-9fe02ebccc35?source=rss-dabec628e4fd------2</link>
            <guid isPermaLink="false">https://medium.com/p/9fe02ebccc35</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[test]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Philippe Simo]]></dc:creator>
            <pubDate>Sun, 19 Apr 2020 11:08:38 GMT</pubDate>
            <atom:updated>2020-05-10T18:20:48.600Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*egK9AuuYm6-m_wGXPczstA.jpeg" /></figure><p>This article is the fourth article of the series <a href="https://medium.com/@philippechampion58/grapql-from-theory-to-real-world-with-spring-boot-d6b46a28027b?source=friends_link&amp;sk=265f0f4063dbea9780de4a55e8370b14">GraphQL, from theory to real-world with Spring-boot</a>. But don’t worry, The stories are designed to be consumed independently from the other stories. You just have to grab the current state of the project by doing this:</p><pre>git clone -n <a href="https://github.com/zero-filtre/springboot-graphql-error-handling.git">https://github.com/zero-filtre/springboot-graphql-error-handling.git</a> &amp;&amp; cd springboot-graphql-error-handling</pre><pre>git checkout 71d5f771bf9a6feaf8a5b7f62947442aace2b127 <br>git switch -c my_experimental_branch</pre><p>In this article, we will see how we can test the resources that we have defined in the project.</p><p>You can check the corresponding video here:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fm_Q6Qx6Y6_U%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dm_Q6Qx6Y6_U&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fm_Q6Qx6Y6_U%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b0589d1d4a176b3e010e7210507d738/href">https://medium.com/media/8b0589d1d4a176b3e010e7210507d738/href</a></iframe><p>We want to make sure the tests are fast, reliable and easy to understand.</p><p>If you have not cloned our project, then you may need these dependencies in your pom.xml</p><pre>&lt;<strong>dependency</strong>&gt;<br>    &lt;<strong>groupId</strong>&gt;com.graphql-java-kickstart&lt;/<strong>groupId</strong>&gt;<br>    &lt;<strong>artifactId</strong>&gt;graphql-spring-boot-starter-test&lt;/<strong>artifactId</strong>&gt;<br>    &lt;<strong>version</strong>&gt;6.0.0&lt;/<strong>version</strong>&gt;<br>    &lt;<strong>scope</strong>&gt;test&lt;/<strong>scope</strong>&gt;<br>&lt;/<strong>dependency</strong>&gt;</pre><p>We have three resources to test, we will then define three GraphQL queries to load from our resources folder.</p><p>If it’s not already done, create this directory in your project: src/test/resources/graphql then create these 3 request file in it.</p><p>create-user.graphql</p><pre><strong>mutation </strong>{<br>    <strong>createUser</strong>(username: <strong>&quot;johndoe&quot;</strong>,password: <strong>&quot;mypassword&quot;</strong>){<br>        <strong>id<br>        username<br>    </strong>}<br>}</pre><p>delete-user.graphql</p><pre><strong>mutation </strong>{<br>    <strong>deleteUser</strong>(username: <strong>&quot;johndoe&quot;</strong>){<br>        <strong>id<br>        username<br>    </strong>}<br>}</pre><p>get-user.graphql</p><pre><strong>query </strong>{<br>    <strong>getUser</strong>(username: <strong>&quot;johndoe&quot;</strong>,password: <strong>&quot;mypassword&quot;</strong>){<br>        <strong>id<br>        username<br>    </strong>}<br>}</pre><p>In our test package we will create 2 classes :<br>One for testing mutations and another one to test queries.</p><p>UserMutationIntTest.java</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa87192300f9d75fb6300fa9c0fefb88/href">https://medium.com/media/fa87192300f9d75fb6300fa9c0fefb88/href</a></iframe><p>Let’s dissect what is happening here.</p><p>We want to test the write requests: AKA the Mutation resolvers.</p><p>As we are using graphql-spring-boot-starter-test we are taking advantage of the embedded JUnit 5 Jupiter engine, and some useful tools to set up graphql easily.</p><p>Especially the @GraphQLTestannotation that is loading only a slice of the Spring-context that is needed for our tests to run.</p><p>This is particularly interesting as our tests need to run fast and not wait for the full heavy Spring context to load.</p><p>Another interesting tool is the GraphQLTestTemplate class that helps us send real GraphQL queries, that we have defined earlier, to tests our resolvers.</p><p>As we want our tests to run as fast as possible, we do not need to load the real underlying beans needed for our resolvers, talking here about the UserService bean. We will just mock them, and tell the mock how to behave when a specific method is called by the resolver.</p><p>Finally, as we have secured our GraphQL resources, we have to use Spring-security to mock users with adequate rights.</p><p>We are following the same logic for testing the read request resolvers, AKA : Query resolvers</p><p>UserQueryIntTest.java</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b6fa772286088bb9e30f0b3c949441c/href">https://medium.com/media/3b6fa772286088bb9e30f0b3c949441c/href</a></iframe><p>And that’s all you have to do to test that your resolvers are responding to the requests you expect them to.</p><p>This is the end of the series, I hope you enjoyed.</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9fe02ebccc35" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/testing-your-graphql-apis-in-a-spring-boot-app-9fe02ebccc35">Testing your GraphQL APIs in a Spring-boot app</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GraphQL, From Theory to Real-World With Spring-Boot]]></title>
            <link>https://medium.com/swlh/grapql-from-theory-to-real-world-with-spring-boot-d6b46a28027b?source=rss-dabec628e4fd------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6b46a28027b</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[graphql]]></category>
            <dc:creator><![CDATA[Philippe Simo]]></dc:creator>
            <pubDate>Sat, 28 Mar 2020 20:24:36 GMT</pubDate>
            <atom:updated>2021-01-06T09:09:41.305Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NZlYJnfQJz-H1jY56pORbA.jpeg" /></figure><p>This article is the first part of a series of articles that we will go through. The series is about mastering the necessary core concepts of the GraphQL Specification to set up a real-world server-side implementation example with spring boot. Each episode is designed to be consumed independently so feel free to start from what interests you the most.</p><ul><li><strong>GraphQL Core concepts </strong>(this one) 📈<br>Getting started with the core concepts of GraphQL to build a real-world example</li><li><a href="https://medium.com/@philippechampion58/understanding-graphql-error-handling-mechanisms-in-spring-boot-604301c9bedb"><strong>First GraphQL API and Efficient graphQL error handling in Spring-boot 🧯</strong></a><br>Set up your Spring-boot project and expose your firsts GraphQL endpoints Get an in-depth understanding of GraphQL error handling mechanisms</li><li><a href="https://medium.com/@philippechampion58/secure-your-graphql-api-within-a-spring-boot-app-72961fbe9232?source=friends_link&amp;sk=447765d64a6a7da1d4d9eec744c78e44"><strong>Secure your graphQL APIs within a Spring-boot</strong></a><strong> ‍👮‍♂️<br></strong>Set up access control level on your APIs to define who can have access to which if your APIs</li><li><a href="https://medium.com/@philippechampion58/testing-your-graphql-apis-in-a-spring-boot-app-9fe02ebccc35?source=friends_link&amp;sk=c91ff02c10402469f6e9c3824a7d89cd"><strong>Testing your graphQL APIs in a Spring-boot app </strong></a><strong>🚀<br></strong>Writing unit and integration tests for your graphQL APIs</li></ul><h3>Overview</h3><p>What is GraphQL?<br>It is a new API Standard developed and used by Facebook since 2012 but open-sourced since 2015. It is a more <strong>flexible and powerful alternative to REST. </strong><br>GraphQL specification has a rapidly growing community and some of the popular companies that use that are <strong>Github</strong>, <strong>Coursera</strong>, <strong>Twitter</strong>, <strong>Shopify</strong>, <strong>yelp</strong>, to name only a few.</p><h3>GraphQL vs REST</h3><p>The idea behind REST is great as it advocates the usage of stateless servers and structured access to resources. But there are shortcomings such as inefficiencies and lack of flexibility encountered by developers and that’s why graphQL was developed for.</p><p>To better illustrate the differences, we will introduce the Social Shopping App (SSApp) that we are going to develop all along with this series.<br><strong>SSApp</strong>:<br>Our app consists of <strong>users</strong>, browsing some shopping <strong>articles </strong>within the app that they can like and buy. Users can sell articles and follow other users so that they can check their activities on the app. That’s it!</p><p>Ok, let’s come back to the illustration, consider we want to display the user home screen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*TLMaenHm9arO4SmWUWbeEw.png" /><figcaption>Sapp User home screen</figcaption></figure><p>To achieve this is REST:</p><p>3 API endpoints from the server:</p><pre>/users/&lt;id&gt;</pre><p>Returning:</p><pre>{<br>  &quot;user&quot;: {<br>    &quot;id&quot;: &quot;flkzopgz12&quot;<br>    &quot;name&quot;: &quot;Samanta Calgon&quot;<br>    &quot;address&quot;: {...}<br>    &quot;birthday&quot;: &quot;May 15, 1995&quot;<br>  }</pre><pre>}</pre><p>Notice we just need the name, but we are fetching useless additional data at this point. We are draining the user data plan. 🤦‍♂️</p><p>Then:</p><pre>/users/&lt;id&gt;/articles?liked=true</pre><p>Returning:</p><pre>{<br>  &quot;articles&quot;: [{<br>    &quot;id&quot;: &quot;dmflgmjlsfgs4z545&quot;<br>    &quot;title&quot;: &quot;Vuicci Sweet Shirt&quot;,<br>    &quot;description&quot;: &quot;Lorem ipsum ...&quot;,<br>    &quot;liked&quot;: &quot;true&quot;<br>    &quot;reviews&quot;: [...]<br>  },{<br>    &quot;id&quot;: &quot;dlkfjge919zzz&quot;<br>    &quot;title&quot;: &quot;Diara Eau de Parfum&quot;,<br>    &quot;description&quot;: &quot;dolor epsumet ...&quot;,<br>    &quot;liked&quot;: &quot;true&quot;<br>    &quot;reviews&quot;: [...]<br>  },{...}<br>  ...</pre><pre>]</pre><pre>}</pre><p>This time also, we just need the title of the articles.</p><p>And</p><pre>/users/&lt;id&gt;/followers</pre><p>Returning:</p><pre>{<br>  &quot;followers&quot;: [{<br>      &quot;id&quot; : &quot;dlkfhosdid2e15&quot;,<br>      &quot;name&quot; : &quot;Klark&quot;,<br>      &quot;address&quot;: { ... },<br>      &quot;birthday&quot;: &quot;January 21, 1998&quot;<br>    },{<br>      &quot;id&quot; : &quot;94erg48h4j&quot;,<br>      &quot;name&quot; : &quot;Rose&quot;,<br>      &quot;address&quot;: { ... },<br>      &quot;birthday&quot;: &quot;January 21, 1998&quot;<br>    },{ ... }    <br>    ... <br>  ]</pre><pre>}</pre><p>Here, we are downloading a lot of data that we don’t need as well.🤦‍♂️</p><p>The fact that we are getting more than the data than we essentially want is called <strong>over fetching</strong>.</p><p>The fact that we can’t get enough information in one request, and need to send many ones to gather all information is known as the <strong>under fetching</strong> problem.</p><p>Yes, you can adapt your REST API to the screen so that it returns only the data needed for display, using the so-called View Models. By doing this, you are highly coupling your views to the endpoints. This way, each time the view will evolve, your API shall evolve too. Which is very bad for API scalability.</p><p>Fortunately, we can solve the above problems with graphQL. 🔥</p><p>We can retrieve what we need by issuing only one request. GraphQL uses only one endpoint, usually /graphql .Sending a request in GrapQL means issuing a post request at this endpoint, and describe in the request body what data do we exactly need from the server.</p><pre>query {<br>  <strong>User</strong>(id: &quot;flkzopgz12&quot;) {<br>    <strong>name</strong><br>    <strong>articles</strong>(liked: True) {<br>      <strong>title</strong><br>    }<br>    <strong>followers</strong>{<br>      <strong>name</strong><br>    }<br>  }<br>}</pre><p>Notice, in words in bold, we tell the server exactly what we need. The server will then process and match this description to the corresponding methods to get the data. Those methods are the <strong>resolvers</strong>. Resolvers will get the data from a DB, another web service, etc then package them into a JSON object and return them to the client.</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;user&quot;: {      <br>      &quot;name&quot;: &quot;Samanta Calgon&quot;, <br>      &quot;articles&quot;: [<br>        { &quot;title&quot;: &quot;Vuicci Sweet Shirt&quot;}<br>        { &quot;title&quot;: &quot;Diara Eau de Parfum&quot;}<br>        { &quot;title&quot;: &quot;Timiland Shoes&quot;}<br>        { &quot;title&quot;: &quot;Lavis Jeans White Vintage&quot;}<br>      ],<br>      &quot;followers&quot;: [<br>        { name: &quot;Klark&quot;},<br>        { name: &quot;Rose&quot;},<br>        { name: &quot;Rick&quot;},<br>        { name: &quot;Josh&quot;},<br>      ]<br>    }<br>  }<br>}</pre><p>The root field of the data part of a graphQL response is data , according to the graphQL specification.</p><p><strong>GraphQL vs REST in a nutshell</strong></p><p>No more over and under fetching<br>No need to adapt the APIs to the view which enables rapid product iterations.</p><p>Moreover, GraphQL uses a strong type system to define the <em>cans</em> and <em>cants</em> of your API. You just have to define your types in a <strong>Schema file</strong>, written in the <a href="https://alligator.io/graphql/graphql-sdl/">Schema Definition Language</a> (SDL). This schema will represent the contract between the Frontend and the backend teams, enabling them to work independently in an API-first like fashion.</p><p>Now that you know why GraphQL is a better alternative to REST, we can now dive into the core concepts of GraphQL.</p><h3>GraphQL Core Concepts</h3><h4><strong>The Schema Definition Language (SDL)</strong></h4><p>It lets us define our schema, which is made up of types.<br>This example illustrates a one-to-many relationship between 2 types:</p><pre>type User {<br>  id: ID!                  # Value generated by the server<br>  name: String!            # String,Int,ID are built-in type<br>  age: Int!                # ! means age is required<br>  articles: [Article!]     # A user can be have many Articles<br>}</pre><pre>type Article {<br>  title: String!<br>  seller: User!            # An article is sold by a User<br>  description: String<br>}</pre><p>In GraphQL, fetched data are not fixed, as you saw earlier, you can decide to retrieve <strong>ONLY</strong> the User articles, or retrieve <strong>JUST</strong> the User age, or even <strong>JUST </strong>the Users articles’ title. The client decides of what he needs.</p><p>One important thing to notice is that because we didn’t define a field passwordin the User type in the schema, this field is unretrievable by the client. No more need to bother with JsonIgnoreconfigurations. That’s the power of the GraphQL strong type system. The server decides of what is possible or not for the client.</p><blockquote>The client decides of what he needs<br>The server decides of what is possible or not for the client</blockquote><h4><strong>The client decides what he needs by sending requests to the server</strong></h4><p>These are the three kind of requests:<br>- <strong>Query</strong>: Retrieve data<br>- <strong>Mutation: </strong>Change data<br>- <strong>Subscription: </strong>Event-based real-time notifications</p><p>Examples:</p><pre><em># Query</em><br><strong>query</strong>{            #<em>starts with the keyword </em><strong><em>query</em></strong><br>  <strong>allUsers </strong>{<br>    <strong>name</strong><br>  }<br>}<br><em># returns</em><br>{<br>  &quot;<strong>allUsers</strong>&quot; : [<br>    {&quot;<strong>name</strong>&quot;:&quot;Samanta Calgon&quot;},<br>    {&quot;<strong>name</strong>&quot;:&quot;Carlos Chavez&quot;},<br>    ...<br>  ]<br>}</pre><pre><em># Mutation</em><br><strong>mutation</strong>{        <em>#starts with the keyword </em><strong><em>mutation</em></strong><br>  <strong>createUser</strong>(<strong>name</strong>: &quot;Miguel Reyes&quot;, <strong>age</strong>: &quot;21&quot;) {<br>    <strong>id</strong><br>  }<br>}<br><em># returns</em><br>{<br>  &quot;<strong>createUser</strong>&quot; : {<br>    &quot;<strong>id</strong>&quot; : &quot;slkdjfr96f4d&quot;<br>  }<br>}</pre><pre><em># Subscription, listening to new articles creation</em><br><strong>susbscription </strong>{    #starts with the keyword <em>susbscription      </em><br>  <strong>newArticle </strong>{<br>    <strong>title</strong><br>    <strong>description<br>    seller </strong>{<strong><br>      name<br>    </strong>}<strong>  <br> </strong> }<br>}<br><em>#When an article is created by another client, </em><br><em>#while the subscription is active, this client will receives<br></em>{<br>  &quot;<strong>Article</strong>&quot; : {<br>    &quot;<strong>title</strong>&quot; : &quot;Marins Jacket, green&quot;,<br>    &quot;<strong>description</strong>&quot; : &quot;Real Marins Jacket refurbished from 2015&quot;<br>    &quot;<strong>seller</strong>&quot; : {<br>      &quot;<strong>name</strong>&quot;:&quot;Carlos Chavez&quot;<br>    }<br>  }<br>}</pre><h4>The Server decides what is possible or not by defining the schema</h4><p>The schema, as mentioned earlier, is the contract between client and server, is written using SDL and defines the capabilities of the API by the means of GraphQL types.</p><p>Functionally, we can see types as of 2 kinds:</p><p>- Types to <strong>describe the data structure</strong>, custom, and built-in ones<br>(User, Article, String, ID, …)<br>- Types to <strong>describe the entry points</strong> exposed by the API<br>(Query, Mutation, and Subscription)</p><p>Let’s illustrate that by defining the schema corresponding to the examples we saw before.</p><pre><em>#Custom and buitl-in Data Structure types</em></pre><pre>type <strong>User </strong>{<br>  id: ID!                  # Value generated by the server<br>  name: String!            # String,Int,ID are built-in type<br>  age: Int!                # ! means the field is required<br>  articles: [<strong>Article</strong>!]     # A user can be have many Articles<br>  followers: [<strong>User</strong>]</pre><pre>}</pre><pre>type <strong>Article </strong>{<br>  title: String!<br>  seller: User!            # An article is sold by a User<br>  description: String<br>}<br></pre><pre>#Types describing entrypoints</pre><pre>type <strong>Query </strong>{<br>  <strong>allUsers</strong>(<strong>last</strong>: Int): [User!]! <em>#</em><strong><em>last </em></strong><em>parameter is optional<br></em>  <strong>user</strong>(<strong>id</strong>: Int): User       <em>#</em><strong><em>No </em></strong><em>&#39;</em><strong><em>!</em></strong><em>&#39;, The returned user can be empty</em></pre><pre><em>  #...</em></pre><pre>}</pre><pre>type <strong>Mutation </strong>{<br>  <strong>createUser</strong>(<strong>name</strong>: String, <strong>age</strong>: Int): User!<br>  <em>#Want the client to create an article ? define the operation here<br>  #...<br></em>}</pre><pre>type <strong>Subscription </strong>{<br>  <strong>newArticle</strong>: Article! </pre><pre>}</pre><p>Now that you have a better vision of what is GraphQL, you are able to step through the next part which is about <a href="https://medium.com/@philippechampion58/understanding-graphql-error-handling-mechanisms-in-spring-boot-604301c9bedb">writing your first GraphQL API with Spring Boot</a></p><h3>Conclusion</h3><p>GraphQL is a better alternative to REST because it offers flexibility and efficiency during application development. This article aimed to prove that while explaining the core concepts of this specification.</p><p>Nevertheless, GraphQL is just a specification, that needs to be implemented for both the client and server-side. We will focus on the server-side, especially with Java and Spring-boot for the next parts of this series.</p><p>Feedback is a Gift 🎁!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6b46a28027b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/grapql-from-theory-to-real-world-with-spring-boot-d6b46a28027b">GraphQL, From Theory to Real-World With Spring-Boot</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Secure your GraphQL API within a Spring-Boot App]]></title>
            <link>https://medium.com/swlh/secure-your-graphql-api-within-a-spring-boot-app-72961fbe9232?source=rss-dabec628e4fd------2</link>
            <guid isPermaLink="false">https://medium.com/p/72961fbe9232</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Philippe Simo]]></dc:creator>
            <pubDate>Sun, 15 Mar 2020 12:10:05 GMT</pubDate>
            <atom:updated>2020-06-13T16:22:22.646Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*SmW_JOl_dUFXFW6RHDzeSA.png" /></figure><p>This is the third episode of the series <a href="https://medium.com/@philippechampion58/grapql-from-theory-to-real-world-with-spring-boot-d6b46a28027b?source=friends_link&amp;sk=265f0f4063dbea9780de4a55e8370b14">GraphQL, from Theory to Real-World with Spring boot</a>. The episodes are designed to be consumed independently, so feel free to start from what interest ou the most.</p><h3>Overview</h3><p>In the <a href="https://medium.com/@philippechampion58/understanding-graphql-error-handling-mechanisms-in-spring-boot-604301c9bedb?source=friends_link&amp;sk=1d97101ee639e362b86fad68c2cc2a14">previous article</a>, we’ve exposed a set of resources via a GraphQL API. Now we want to secure them to prevent unauthenticated and unauthorized access.</p><h4>TL;DR</h4><p>Check the corresponding video.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F1PKqY50IjBw%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D1PKqY50IjBw&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F1PKqY50IjBw%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/107126a3beecfc55e9ae3471551d755c/href">https://medium.com/media/107126a3beecfc55e9ae3471551d755c/href</a></iframe><blockquote>NOTE: Reading the previous article IS NOT mandatory, they are designed to be consumed independently by just checking out the <a href="https://github.com/zero-filtre/springboot-graphql-error-handling">codebase on GitHub.</a></blockquote><p>Spring security offers us the WebSecurityConfigurerAdapter::configure method to configure our app security. It gives us a way to define the access level of some resources based on URLs. Unfortunately, this is not a mechanism that fits well with the GraphQL protocol as it does with REST APIs.</p><p>Actually, graphQL is using only one endpoint, usually /graphql. Hence we cannot secure our resources based on URLs. As we want some resources to be either accessed only by administrators, or by authenticated users or even opened to the public.</p><p>But it becomes possible if we use annotations on resolvers methods, coupled with Aspect-Oriented Programming (AOP), and that’s what we are going to do.</p><p>So, at the end of this article, you will know how to:</p><ul><li>Set up an aspect with Spring AOP,</li><li>Use aspect-oriented programming coupled with custom annotations to secure your resources,</li><li>Write tests to check your GraphQL API</li></ul><h3>Project Setup</h3><p>Clone the <a href="https://github.com/zero-filtre/springboot-graphql-error-handling">code bas</a>e that we had in the<a href="https://medium.com/@philippechampion58/understanding-graphql-error-handling-mechanisms-in-spring-boot-604301c9bedb?source=friends_link&amp;sk=1d97101ee639e362b86fad68c2cc2a14"> previous article</a>:</p><pre>git clone -n <a href="https://github.com/zero-filtre/springboot-graphql-error-handling.git">https://github.com/zero-filtre/springboot-graphql-error-handling.git</a> &amp;&amp; cd springboot-graphql-error-handling/</pre><pre>git checkout bd7a0b5c039c610de9c8355be0d1c5f5e5484655</pre><pre>git switch -c my_experimental_branch</pre><p>We will make the resources:<br><strong>createUser(username:string, password:string) </strong>public,</p><p><strong>getUser(username:string, password:string) </strong>available for authenticated users only, and we will create an additional resource:</p><p><strong>deleteUser(username:string)</strong>, to be available for admin users only.</p><p>Add the following dependencies to the pom.xml</p><pre>...<br>&lt;dependency&gt;<br>  &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>  &lt;artifactId&gt;spring-boot-starter-security&lt;/artifactId&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>  &lt;groupId&gt;org.springframework&lt;/groupId&gt;<br>  &lt;artifactId&gt;spring-aspects&lt;/artifactId&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>  &lt;groupId&gt;org.springframework.security&lt;/groupId&gt;<br>  &lt;artifactId&gt;spring-security-test&lt;/artifactId&gt;<br>  &lt;scope&gt;test&lt;/scope&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>  &lt;groupId&gt;junit&lt;/groupId&gt;<br>  &lt;artifactId&gt;junit&lt;/artifactId&gt;<br>  &lt;scope&gt;test&lt;/scope&gt;<br>&lt;/dependency&gt;<br>...</pre><p>Then we add the additional deleteUser resource which matches the following resolver method in UserMutation.java:</p><pre>public User deleteUser(String username) {<br>   return userService.deleteUser(username);<br>}</pre><p>Don’t forget to define the UserService::delete method, which just removes the user corresponding to that username from the in-memory List&lt;User&gt; users and returns information about the deleted user.</p><p>Add <strong>deleteUser</strong> resource spec to the schema definition file: src/main/resources/UserQL.graphqls :</p><pre>type Mutation {<br>    ...<br>    deleteUser(username: String!): User<br>}</pre><h3>Securing the resources</h3><p>The strategy consists of:</p><ul><li>Authorizing all requests related to GraphQL: /graphql</li><li>Then, thanks to <strong>custom annotations</strong>, specify, at the method level in resolvers, which methods are public<strong>, </strong>which ones <strong>should be accessed only by authenticated users, and </strong>which ones <strong>should only be accessed by users with specific roles such as ADMIN.</strong></li><li>Whilst with aspects, we will check if our annotations are applied or not and throw exceptions accordingly.</li></ul><p>Let’s create the security configuration file: SecurityConfig.java</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/560d7cb6294cfae060fd7f55d4d83f71/href">https://medium.com/media/560d7cb6294cfae060fd7f55d4d83f71/href</a></iframe><p>This config tells our app to authorize all requests related to GraphQL so that we can check them at the resolver level with annotations.</p><p>We will have two annotations:<br> @AdminSecured appended to admin resources, and<br> @Unsecured appended to public resources. <br>All other endpoints will, by default, need authenticated users access. <br>It’s always better to forget to make a resource unsecured than to forget to secure it 😁</p><p>AdminSecured.java</p><pre><em>/**<br> * This annotation will trigger Admin security check for<br> * the GraphQL resolver method where it is marked.<br> */<br></em>@Retention(RetentionPolicy.<em>RUNTIME</em>)<br>@Target(ElementType.<em>METHOD</em>)<br>public @interface AdminSecured {}</pre><p>Unsecured.java</p><pre><em>/**<br> * This annotation will disable security check for<br> * the GraphQL resolver method where it is marked.<br> */<br></em>@Retention(RetentionPolicy.<em>RUNTIME</em>)<br>@Target(ElementType.<em>METHOD</em>)<br>public @interface Unsecured {}</pre><p>Now go on and annotate the resolver methods accordingly:</p><pre>@Unsecured<br>public User createUser(String username, String password) {<br>    return userService.createUser(username, password);<br>}</pre><pre>@AdminSecured<br>public User deleteUser(String username) {<br>    return userService.deleteUser(username);<br>}</pre><p>UserQuery::getUser will be set as secured by default.</p><p>Let’s define the aspect that will scan these annotations.<br>First, we need to Enable AOP in the main application class, by adding @EnableAspectJAutoProxy annotation like so:</p><pre>@SpringBootApplication<br><strong>@EnableAspectJAutoProxy</strong><br>public class SampleGraphqlErrorHandlingApplication {<br>    public static void main(String[] args) {        SpringApplication.<em>run</em>(SampleGraphqlErrorHandlingApplication.class, args);<br>    }<br>}</pre><p>Then the aspect class… But wait! ☝🏾, What’s an aspect? 🤔</p><p>Aspects are related to Aspect-Oriented Programming (AOP) which <em>g</em>ives you a way to encapsulate or modularize a behavior that is transversal and repeated across several types of objects and that is, normally, not easy to encapsulate in its own module.</p><p>Usually, those behaviors (logging, caching, transaction management…) are not related to business logic and they are so-called aspects.</p><blockquote>An aspect is a common feature that’s typically scattered across methods, classes, object hierarchies, or even entire object models [3] .</blockquote><p><strong>Example:<br></strong>AOP provides you with programmatic control to specify that you want calls:</p><ul><li>To all methods annotated @Timedto trigger a timer before executing the actual body of that code.</li><li>To all methods classes in the package xxx.bank.accountto trigger a specific additional security check</li><li>etc</li></ul><p>Without repeating yourself 😎</p><p>We are going to do something similar with our Aspect.</p><p>Yes, you have guessed it right, our aspect is about security check based on annotations.</p><p>SecurityGraphQLAspect.java</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f308fcfaa877191cc1d6c62f62b26480/href">https://medium.com/media/f308fcfaa877191cc1d6c62f62b26480/href</a></iframe><p>Don’t worry, It seems complicated but it’s actually pretty simple.<br> Let’s go through each part of it to understand what it’s being done here.</p><p>First, As we defined this spring component as @Aspect, it becomes an interceptor and we want it to be the first to be triggered, before any other interceptor, since it is our security guarantor. That’s why we use @Order(1)</p><p>The first method doSecurityCheckis annotated with @Beforewhich is an <strong><em>Advice</em></strong>, which means, according to AOP terminology: <strong>action taken by the aspect at a specific point during the execution of the program</strong>.</p><p>The @Before advice lets the action being executed before the specified <strong><em>PointCut</em></strong>s, which helps to <strong>categorize elements of the program that the aspect will watch.</strong></p><p>doSecurityCheckis executed before<strong> all GraphQL resolvers methods</strong> that <strong>are defined within our project</strong> and that<strong> are not annotated as unsecured</strong>. These categories are then defined with the help of @PointCut.<br>doSecurityCheckchecks the Spring security context to make sure the user is authenticated.</p><p>Similarly: doAdminSecurityCheck is executed before <strong>all methods annotated as AdminSecured.<br></strong>doAdminSecurityCheckchecks the Spring security context to make sure the user has the ADMIN role.</p><p>This is the code for the referenced UnauthenticatedAccessException.java:</p><pre>public class UnauthenticatedAccessException extends RuntimeException implements GraphQLError {<br><br>    public UnauthenticatedAccessException(String msg) {<br>        super(msg);<br>    }<br><br>    @Override<br>    public List&lt;SourceLocation&gt; getLocations() { return null; }<br><br>    @Override<br>    public ErrorClassification getErrorType() { return null; }<br>}</pre><p>That’s it! 🏁</p><p>Now let’s start the app, launch <a href="http://locahost:8080/graphiql">http://locahost:8080/graphiql</a> and:</p><ul><li>Create a user:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/0*3sqVJxBQ5gkQZuC_" /></figure><p>Everything works as expected ✌🏾.</p><ul><li>Delete that user:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JcKCaksW7DDtEmCg" /></figure><p>We do not have the right to do that as expected ✌🏾.</p><ul><li>Get users:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*h7ylf95s0nZj5QEU" /></figure><p>We need to log in first as expected ✌🏾.</p><p>Let’s test the remaining cases programmatically so that you can automate it in a pipeline and earn some time.</p><p>GraphQLSecurityTests.java</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/967ce40e4591bcfdbfcf1c1f287a4e3f/href">https://medium.com/media/967ce40e4591bcfdbfcf1c1f287a4e3f/href</a></iframe><p>Notice that we restart the context after each test method with @DirtiesContext to make sure every method runs in a clean, not polluted context. But you should not abuse this, as it increases considerably your tests execution time.<br>Run the test and should have a 100% success.</p><p>Now our endpoints are secured 😎.</p><h3>Conclusion</h3><p>GraphQL APIs are great but are different in so many ways from REST APIs, and the way to handle the security is no exception.</p><p>That’s why in this article, we saw how to use aspect-oriented programming coupled with custom annotations to secure our resources. Additionally, we also wrote tests to check the whole stuff.</p><p>I hope you enjoyed it.</p><p>In the <a href="https://medium.com/@philippechampion58/testing-your-graphql-apis-in-a-spring-boot-app-9fe02ebccc35?source=friends_link&amp;sk=c91ff02c10402469f6e9c3824a7d89cd">next article</a>, we will describe a strategy and apply a strategy to write fast, bulletproof tests for your GraphQL APIs with Spring boot.</p><p>Don’t forget, Feedback is a gift 🎁!</p><p><em>References:</em></p><p>[1] <a href="https://docs.spring.io/spring/docs/2.0.x/reference/aop.html">https://docs.spring.io/spring/docs/2.0.x/reference/aop.html</a></p><p>[2] <a href="https://mi3o.com/spring-graphql-security/">https://mi3o.com/spring-graphql-security/</a></p><p>[3] <a href="https://docs.jboss.org/aop/1.0/aspect-framework/userguide/en/html/what.html">https://docs.jboss.org/aop/1.0/aspect-framework/userguide/en/html/what.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72961fbe9232" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/secure-your-graphql-api-within-a-spring-boot-app-72961fbe9232">Secure your GraphQL API within a Spring-Boot App</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding GraphQL Error Handling Mechanisms in Spring-Boot]]></title>
            <link>https://medium.com/swlh/understanding-graphql-error-handling-mechanisms-in-spring-boot-604301c9bedb?source=rss-dabec628e4fd------2</link>
            <guid isPermaLink="false">https://medium.com/p/604301c9bedb</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[grapqhql]]></category>
            <category><![CDATA[exception-handling]]></category>
            <category><![CDATA[error-handling]]></category>
            <dc:creator><![CDATA[Philippe Simo]]></dc:creator>
            <pubDate>Sun, 16 Feb 2020 18:54:34 GMT</pubDate>
            <atom:updated>2021-01-06T09:09:19.009Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*I2xagDD328J2GBBaovLfiA.png" /></figure><h3>Overview</h3><p>This article is the second part of the series <a href="https://medium.com/@philippechampion58/grapql-from-theory-to-real-world-with-spring-boot-d6b46a28027b">GraphQL, from Theory to real-world with Spring boot</a>.</p><p>Today’s episode is about setting up your Spring-boot project to host your first GraphQL API entry points then call them using the web-based tool GraphiQL.</p><p>It also aims to bring an in-depth understanding of how the <a href="https://github.com/graphql-java/graphql-java">Graphql Java Implementation</a>(graphql-java) deals with error handling and especially how to rely on that, by using the <a href="https://github.com/graphql-java-kickstart/graphql-spring-boot">GraphQL Spring Framework boot starter</a>, to handle efficiently errors within our app, as this is an aspect that is often overlooked by early graphql adopters.</p><h4>TL;DR</h4><p>Check the corresponding video</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FlxOXDI_dvt8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DlxOXDI_dvt8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FlxOXDI_dvt8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/38a8aa07563461bb03f1168f9d07cdf4/href">https://medium.com/media/38a8aa07563461bb03f1168f9d07cdf4/href</a></iframe><p>Before we start, let’s introduce some context.</p><h3>GraphQL quick summary</h3><p>GraphQL is a specification that defines not only a new query language for APIs but also how data is returned in response to these queries.<br>It is an alternative to using Restful APIs in the sense that it solves some of their drawbacks with new features such as these described ones:</p><ul><li>The client has full control over the data returned to him, he receives only what he needs, no more, no less. No unnecessary data is therefore loaded onto the network. No over-etching.</li><li>The client can request several resources at once in a single request, no need to send multiple requests. Ideal for slow mobile connections.</li><li>The server defines what is possible or not with the notion of types, to force the client to request only what is possible.</li></ul><h3>With great power comes great responsibilities</h3><p>According to the features mentioned above, the client must be highly considered when setting up such an API. It is more than important to return a response format that is consistent and predictable across several scenarios, to make it easier for the customer to consume the response.</p><p>According to the specification, a GraphQL response should follow this pattern:</p><p><strong>A GraphQL response might always have the HTTP status 200 OK. </strong><br>HTTP error codes are not relevant when using GraphQL because,<br>If a request fails, the JSON payload of the server’s response will contain a root field called “<strong><em>errors</em></strong>” that contains precise information about the problems that occurred on the server-side.<br>Moreover, since GraphQL allows for multiple operations to be sent in the same request, it’s well possible that a request only partially fails and returns actual data and errors.</p><p><strong>The response body could contain the following fields:</strong><br>“<strong><em>data</em></strong>”: where the data resulting from the operation reside.<br>“<strong><em>errors</em></strong>”: where all the errors are filled in.<br>“<strong><em>extensions</em></strong>”: for additional information about the response</p><p><strong>The “<em>errors</em>” field, should contain the following fields </strong>:<br>“<strong><em>message</em></strong>”: a key describing the error<br>“<strong><em>locations</em></strong>”: a list of graph coordinates where the errors have occurred.<br>“<strong><em>path</em></strong>”: a key describing the absolute path from the root of the graph to the field where an error has occurred.<br>“<strong><em>extensions</em></strong>” key for the metadata related to the errors.</p><p>You can learn more about GraphQL response format by referring to the <a href="https://spec.graphql.org/June2018/#sec-Response">specification part that deals with this topic</a>.</p><p>As far as we are concerned, we will just focus on the “<strong>errors</strong>” key.</p><p>By relying on the graphql-java and graphql-spring-boot within a spring-boot application, we will dissect the underlying mechanism of errors handling within these libraries to let you know what are your possibilities when it comes to customizing some of the default error handling mechanisms.</p><h3>Application Set up</h3><p>We will use a simple spring-boot <strong>sample-graphql-error-handling </strong>that will expose two endpoints:</p><p><strong>createUser(username:string, password:string)</strong> that fails if a user is already registered with the same username.</p><p><strong>getUser(username:string,password:string) </strong>that fails if no user is existing for the given username.</p><p>Generate the project using <a href="https://start.spring.io/">Spring Initializr</a> and add the following dependencies to the pom.xml file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/03979edf8a4af44297e5cfcf362bc217/href">https://medium.com/media/03979edf8a4af44297e5cfcf362bc217/href</a></iframe><p>Our User model Class: User.java</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e2fdfc40204431280ac47be1b7bf3f72/href">https://medium.com/media/e2fdfc40204431280ac47be1b7bf3f72/href</a></iframe><p>The Schema definition file: src/main/resources/UserQL.graphqls</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc0358f235547018845702701d410394/href">https://medium.com/media/bc0358f235547018845702701d410394/href</a></iframe><p>The schema speaks for itself, we will have a read request getUser which will return a User corresponding to the username and password given as parameters, and a write request which will register a User with its credentials as parameters.</p><p>We will use a service class, acting as our business logic that will maintain a list of in-memory users. This service will be injected into our resolvers later.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b34b16795a866db16ae516c0da8eef7a/href">https://medium.com/media/b34b16795a866db16ae516c0da8eef7a/href</a></iframe><p>The createUser method will return a UserAlreadyExistsException if a user already exists. Similarly, the getUsermethod will return a UserNotFoundException in case no user is found.</p><p>Next, we have the code of our exceptions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c2b63bf4b10db5fa9bf00d4c30ca2040/href">https://medium.com/media/c2b63bf4b10db5fa9bf00d4c30ca2040/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a673e1a4b3944337ebf173fa4a437f3/href">https://medium.com/media/9a673e1a4b3944337ebf173fa4a437f3/href</a></iframe><p>We will rely on these customized exceptions to return relevant information to the customer.</p><p>Finally, the resolvers code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ab371c798176f9a4325bf13c01963f6/href">https://medium.com/media/1ab371c798176f9a4325bf13c01963f6/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f1f25050c4e7c21849c8603aac3a571/href">https://medium.com/media/1f1f25050c4e7c21849c8603aac3a571/href</a></iframe><p>Now that the project is set up, we can start sending the requests and analyze the errors. Run the spring boot app and launch the graphiql tool within the browser with: localhost:8080/graphiqlif you are running on the local machine with the default spring boot app port.</p><h3>The generic error (case#1)</h3><p>Within the graphiql tool, let’s start by creating a user:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c5422f8448a26e74a509de567b44196/href">https://medium.com/media/0c5422f8448a26e74a509de567b44196/href</a></iframe><p>Everything is OK and the user is indeed created as confirmed by the answer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/0*sQ2r8zJAR-ke_G_R" /><figcaption>Response received when creating a user</figcaption></figure><p>If we try to get a non-existing user:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f610ac31c6ce543a13c11040057012b/href">https://medium.com/media/1f610ac31c6ce543a13c11040057012b/href</a></iframe><p>The request results in the following error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/0*30BZQYWDtA5MI1Yj" /><figcaption>Generic error returned</figcaption></figure><p>Not only are the details as defined by the specification missing, but the error message is also inconsistent, as it indicates a server-side error yet it is a client-side error.<br>Also, if we try to create a user that is already existing:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c5422f8448a26e74a509de567b44196/href">https://medium.com/media/0c5422f8448a26e74a509de567b44196/href</a></iframe><p>We get the exact same error response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/0*30BZQYWDtA5MI1Yj" /><figcaption>Generic error returned</figcaption></figure><p>Let’s consider what just happened as <strong>CASE #1</strong></p><p>For <strong>CASE #2</strong>: We need to customize the information according to the error that occurred while giving the client additional information about what happened in the backend so that he can react accordingly.</p><h3>Customizing errors (case#2)</h3><p>We’ve already taken a step forward by defining and throwing problem-related customized exceptions. However, these exceptions need to be transformed into GraphQL errors that respect the standard format before being sent to the client.</p><p>graphql-java provides the GraphQLError interface representing a GraphQL standard error that our exceptions will implement.</p><p>Our exceptions become:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/914b18142ed94fa37064be59c48a2b37/href">https://medium.com/media/914b18142ed94fa37064be59c48a2b37/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/60da13c52d4e30d7b4b8b1b8aa670da6/href">https://medium.com/media/60da13c52d4e30d7b4b8b1b8aa670da6/href</a></iframe><p>Overriding getLocations() and getErrorType() is mandatory.</p><p>We will just return nullin these methods because they are ignored by the default error handler anyway. We will see why later.</p><p>In the case of wrong identification data, we want to add an “<strong>invalidField</strong>” field under the key “<strong>extensions</strong>” of the error to indicate to the customer which field is in error and needs to be corrected. This is why we redefine the getExtensions()method in UserNotFoundException</p><p>Don’t forget to change the instantiation of the exception in UserService.java</p><pre><strong>throw new UserNotFoundException</strong>(“We were unable to find a user with the provided credentials”, “username”);</pre><p>Let’s start the application again and run the same test scenario with graphiql to compare the results.<br>Let’s start by creating a user, the answer is, unsurprisingly, this one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/0*Z2sAOf2HBKv3cHj8" /></figure><p>Then, if you try to retrieve a user that doesn’t exist, the request results in the following error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/0*DMisGK5Fd97sOMKu" /></figure><p>Note the invalid field present in the <strong>extensions </strong>block of the result.</p><p>Also, If we try to create a user with an existing username, the response is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gF2OoTMaQs1LiqIL" /></figure><p>Let’s dissect what just happened in both cases #1 and #2:</p><p>When we throw an exception while fetching data:</p><ol><li><strong>The exception is handled by default by the </strong><strong>SimpleDataFetcherExceptionHandler</strong></li></ol><p>The handler wraps <strong>4 things</strong>: the thrown <strong>custom exception</strong> (the RuntimeException), the <strong>exception message</strong>, the <strong>error locations, </strong>and the <strong>extensions</strong>, within an ExceptionWhileDataFetchingerror (which is an implementation of the GraphQLErrorinterface).<br>Then, the ExceptionWhileDataFetchingis added to the list of errors of the query result. As we can see in the following <a href="https://github.com/graphql-java/graphql-java/blob/master/src/main/java/graphql/execution/SimpleDataFetcherExceptionHandler.java">SimpleDataFetcherExceptionHandler</a> code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/169a9b1f3d3c4370b4830decbdcc58fa/href">https://medium.com/media/169a9b1f3d3c4370b4830decbdcc58fa/href</a></iframe><p>At line 10, a new ExceptionWhileDataFetchingis constructed with the error path, our exception, and the sourceLocation.</p><p><em>Remember I told you the methods </em><em>getLocations() and </em><em>getErrorType() of our exception were ignored?<br>Well here’s why:</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a4c4746f60cd37c1667ea30164d5c92/href">https://medium.com/media/1a4c4746f60cd37c1667ea30164d5c92/href</a></iframe><p><em>In this code snippet from the </em><a href="https://github.com/graphql-java/graphql-java/blob/master/src/main/java/graphql/ExceptionWhileDataFetching.java"><em>ExceptionWhileDataFetching</em></a><em> class, only the methods </em><em>getMessage() and </em><em>getExtensions() are called, the path and the sourceLocation are already provided upon class instantiation.</em></p><p>2. <strong>The DefaultGraphQLErrorHandler</strong></p><p>After the SimpleDataFetcherExceptionHandler process, another handler, defined by the <strong>graphql-spring-boot</strong> library comes into action to handle the returned list of errors. <br>He is the GraphQLErrorHandler: the default implementation is the DefaultGraphQLErrorHandler</p><p>These 2 steps can be illustrated as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kT6gYRkoJycrhbg-0TjuMQ.png" /><figcaption>The Simple DataFetcherExceptionHandler process</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yea_Jb-2wYm5q-kta951Tw.png" /><figcaption>The DefaultGraphQLErrorHandler process</figcaption></figure><p><strong>In case#1</strong>: Our custom exceptions <strong>were not</strong> instances of <strong>GraphQLErrors</strong>, the DefaultGraphQLErrorHandler considered them as internal server errors, containing<strong> details that should not reach the client</strong>. They were filtered and converted to GenericGraphQLError as illustrated.</p><p><strong>In case#2</strong>: Our custom exceptions <strong>were </strong>instances of <strong>GraphQLErrors</strong>, hence they were not reduced to Generic graphQL errors.</p><p>This behavior is described in the DefaultGraphQLErrorHandler::processErrors()method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5cd6a0262072a2aa2eb390a8402d43a1/href">https://medium.com/media/5cd6a0262072a2aa2eb390a8402d43a1/href</a></iframe><p>Now we clearly understand why we get such a useful error response and a valid format for <strong>case#2</strong>.</p><p>If the SimpleDataFetcherExceptionHandler behavior doesn’t fit your use case, you can create a CustomDataFetcherExceptionHandlerimplementing DataFectcherExceptionHandler, then define your own logic and throw something different than an ExceptionWhileDataFetchingGraphQLError.</p><p>However, this is not something I will advise as you can find yourself breaking the rules of the GraphQL Specification by sending non-standard error messages. Unless you really understand what you are trying to implement.</p><p>Besides, customizing this behavior implies <a href="https://www.graphql-java.com/documentation/v11/execution/">modifying the query execution strategy</a>. As graphql-spring-boot integration is relying on graphql-java to implement the query execution strategy, you will have to deal with them, which, IMHO, does not worth it, as they already implement a pretty good behavior.</p><p>Similarly, If the DefaultGraphQLErrorHandlerbehavior doesn’t fit your use case, you can create a CustomGraphQLErrorHandler implementing GraphQLErrorHandler, then define your own logic and handle GraphQLErrors differently.</p><p>Let’s supposed we are not satisfied by the string: Exception while fetching data (/xxxx) which is automatically appended to the error message sent to the user, and we just want our original message in the error, without any fancies. We will send our unwrapped original custom exception to the final user by defining a CustomGraphQLErrorHandler.</p><h3>Sending unwrapped exception</h3><p>We create the CustomGraphErrorHandler as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b58df175183bb1efb983039b8c9932f3/href">https://medium.com/media/b58df175183bb1efb983039b8c9932f3/href</a></iframe><p>We override the processErrorsmethod by telling the handler to: first check if the exception is an ExceptionWhileDataFetching then extract our original exception( UserNotFoundException, UserExistsException …) and return it. Otherwise, the handler will just return the received exception as it is.</p><p>If we try to find a non-existing user, we get the following error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/0*BfW6m4elgY0BEhDI" /></figure><p>As our exceptions are sent back to the user unwrapped, the message is now concise and precise.</p><h3>Conclusion</h3><p>In this article, we were focusing two notions:</p><p>Setting up your Spring-boot project to host your first GraphQL API entry points,</p><p>Understanding how the graphql-java implementation and graphql-spring-boot handle errors triggered within an application.</p><p>We have covered the following sections:</p><ul><li>Setting up a sample project</li><li>Understanding the standard Graphql error response format</li><li>Diving into the mechanisms behind generic graphql errors and more tailored ones</li><li>Adding additional custom information to the error</li><li>Getting to know the possibilities of further error customizations.</li></ul><p>The Github repo about this article is available <a href="https://github.com/zero-filtre/springboot-graphql-error-handling"><strong><em>here</em></strong></a>.</p><p>In <a href="https://medium.com/@philippechampion58/secure-your-graphql-api-within-a-spring-boot-app-72961fbe9232">our next article</a>, we will see how to Secure our APIs with pretty simple steps.</p><p>Thanks for reading, feedback is a gift 🎁.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=604301c9bedb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/understanding-graphql-error-handling-mechanisms-in-spring-boot-604301c9bedb">Understanding GraphQL Error Handling Mechanisms in Spring-Boot</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>