Welcome to Grafbase!

This quickstart will walkthrough building your GraphQL backend and running it locally. You will learn how to query, mutate, deploy, create branches, protect your data with auth, and invite your team to collaborate.

We will build the backend for BaseNews — a site where we can post new links to articles, upvote, and comment.

You don't need a solid understanding of GraphQL to get started with Grafbase.

NOTE: This quickstart is based on the schema.graphql configuration approach.

Youtube video thumbnail

We'll begin creating a new project using the command line:

npx grafbase init basenews

You should now see the directory basenews and in it, grafbase/schema.graphql. Open this file in your code editor to get started.

If you already have a frontend project you want to add Grafbase to, you can do that too.

If you already know how to write GraphQL schemas then adopting Grafbase will mean you don't need to learn another schema definition language.

We'll use the GraphQL Schema Definition Language to define all of our types, fields, and scalars.

GraphQL SDL

Grafbase provides various GraphQL directives that we can use to reference relationships, unique fields, CRUD capabilities, and more.

We'll use the custom @model directive in the GraphQL SDL below. This tells Grafbase to create CRUD APIs for the following types:

  • Post
  • Comment
type Post @model {
}

type Comment @model {
}

Now add 2 fields to the Post model for title and url. Both of these fields will be non-nullable, but only url will be unique.

type Post @model {
  title: String!
  url: String! @unique
}

You'll notice above that we used the String scalar for both of these types. Grafbase has an extended set of scalars that you can use to enhance the validation of values.

Right now the url field would accept any unique String. Instead let's only allow actual URLs by changing the scalar to URL:

type Post @model {
  title: String!
  url: URL! @unique
}

Next we'll add a non-nullable field for message to Comment:

type Comment @model {
  message: String!
}

Finally, let's create the relationships between these models:

  • Post has many Comments
  • Comment belongs to one Post
type Post @model {
  title: String!
  url: URL! @unique
  comments: [Comment]
}

type Comment @model {
  message: String!
  post: Post
}

That's it! You just created the schema for your first GraphQL backend without having to write any complex resolvers.

You can now use the Grafbase CLI to run your GraphQL API locally. The CLI will automatically detect the schema (and any changes) for the file grafbase/schema.graphql.

Execute the following:

npx grafbase dev

Now you can visit http://localhost:4000 to access your GraphQL API, and explore the documentation for your API.

Grafbase Playground

Was this page helpful?