Exit e-book
Show all chapters
The first query
The first query

Sign up to our Newsletter

Signing up to our newsletter allows you to read all our ebooks.

    How To GraphQL with Scala

    The first query


    Our goal for this chapter is to run the following query:

    query {
    allLinks {

    The expected response is a list of links fetched from the database.

    Define a model

    Before we will add the first model, please decide where all models will be stored. I have one recommendation but of course, you can place all models in the place you want.

    Create models package and package. scala with content:

    package com.howtographql.scala.sangria
    package object models {


    All of the domain’s models will be placed in this file, so it will be easy to find them and in case of this tutorial easy to compare different versions and recognize if something changes. Now we can get back to creating our first model. Let’s start by defining a really basic model Link.

    In the file created above add the following case class:

    case class Link(id: Int, url: String, description: String) 

    As you can see, Link model has fewer fields than in the schema you saw in the first chapter, but no worries, we will improve the model in the future. Now we will focus on completing the execution stack so it would be better to keep this model simple. Add Link support to database Our simple database has to support this model and provide some data as well. Add following changes to the DBSchema. scala:

    import com.howtographql.scala.sangria.models._
    //In the object body:
    class LinksTable(tag: Tag) extends Table[Link](tag, "LINKS"){
        def id = column[Int]("ID", O.PrimaryKey, O.AutoInc)
        def url = column[String]("URL")
        def description = column[String]("DESCRIPTION")
        def * = (id, url, description).mapTo[Link]
    val Links = TableQuery[LinksTable]
    val databaseSetup = DBIO.seq(
        Links forceInsertAll Seq(
          Link(1, "http://howtographql.com", "Awesome community
    driven GraphQL tutorial"),
          Link(2, "http://graphql.org", "Official GraphQL web
          Link(3, "https://facebook.github.io/graphql/", "GraphQL

    We have just added the database definition of our first model.

    1. Defines mapping to database table,
    2. Gives us a helper we will use to access data in this table.
    3. The last change is responsible for creating the schema and adding three entities to the database. Don’t forget to replace the empty function which was provided by the template