Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

GraphQL Schema Basics

1. Introduction

GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data. The schema is a core component of GraphQL, defining the structure of your API.

2. What is a Schema?

A schema defines the types and their relationships in a GraphQL API. It serves as a contract between the client and server, specifying how clients can access the data.

Note: The schema is usually written in the Schema Definition Language (SDL).

3. Schema Types

GraphQL schemas consist of several types:

  • Object Types
  • Query Types
  • Mutation Types
  • Input Types
  • Scalar Types
  • Enum Types

4. Defining Types

To define an object type in GraphQL, you use the following syntax:


type User {
    id: ID!
    name: String!
    email: String!
}
            

In this example, we've defined a User type with three fields: id, name, and email.

5. Queries and Mutations

Queries are used to fetch data, while mutations are used to modify data. Here’s how to define both:


type Query {
    user(id: ID!): User
}

type Mutation {
    createUser(name: String!, email: String!): User
}
            

6. Best Practices

  • Use descriptive names for types and fields.
  • Keep your schema simple and focused.
  • Document your schema effectively.
  • Version your schema as your API evolves.

7. FAQ

What is GraphQL schema?

A GraphQL schema is a blueprint that defines the types and operations available in a GraphQL API.

How do I define a new type in GraphQL?

You define a new type using the type keyword followed by the type name and its fields.

Can I have multiple types in a schema?

Yes, a GraphQL schema can have multiple object types, enums, inputs, etc.