DEV Community 👩‍💻👨‍💻

Cover image for LERN GQL WITH ME: Schema Definition Language
Darshan-Bajeja
Darshan-Bajeja

Posted on

LERN GQL WITH ME: Schema Definition Language

(Examples taken from howtographql)

Welcome to the second part of Learn GraphQL With Me. In this post we will be learning about some core concepts related to GraphQL. These concepts are language independent, so it means that you do not need to know any particular language to understand these, as these are GraphQL specific, and once understood can be implemented in any language.

One thing to keep in mind here is that as GraphQL is different from REST and SOAP, you need to try to understand this little differently as GraphQL has its own specific concepts, which are independent of any other type of API.

So let's finally begin learning GraphQL.

Schema Definition Language (SDL)

GraphQL has its own type system for defining schemas, like we do for modelling the database tables (for SQL) and documents (for NoSQL). This is called the SDL or the Schema Definition Language.

So this is how you define schemas or types in GraphQL:

type Person {
    name: String!
    age: Int!
}
Enter fullscreen mode Exit fullscreen mode

Notice how we have ! after the data types String and Int. This tells that 'name' and 'age' are compulsory. If we just wrote name as name: String, this would have meant that it is not compulsory that Person has a name.

Let's also add a Post type to our schema:

type Post {
    title: String!
}
Enter fullscreen mode Exit fullscreen mode

Now what if we want to have relations between the Post and the Person type. We can now use Person and Post as a data type, like we use String, Int. So let's define an author field, which is of type Person.

type Post {
    title: String!
    author: Person!
}
Enter fullscreen mode Exit fullscreen mode

This tells that a Post will have an author who will be a Person. But we also want to say that a Person can write many posts, so how do we do that. Let's add a posts field to Person type which will be an array of type Post.

type Person {
    name: String!
    age: Int!
    posts: [Post!]!
}
Enter fullscreen mode Exit fullscreen mode

Notice how we have ! after Post as well as after ], this tells that the array is compulsory as well as there has to be some data of type Post inside it.

Top comments (0)

Visualizing Promises and Async/Await 🤯

async await

☝️ Check out this all-time classic DEV post