Проектирование первой схемы GraphQL
Научитесь определять основные типы схемы и поля, а также разберитесь с языком определения схемы (SDL).
«Проектирование первой схемы GraphQL» — бесплатный урок GraphQL APIs with Spring Boot на CoddyKit. Это урок 3 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения GraphQL APIs with Spring Boot, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс GraphQL APIs with Spring Boot содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
What's a GraphQL Schema?
A GraphQL schema is the blueprint of your API: it defines what data clients can ask for and how it’s structured. It’s the core of every GraphQL service.
Meet SDL: Schema Language
You write schemas in the Schema Definition Language (SDL) — a simple, readable syntax for declaring object types, their fields, and how they relate.
Building Blocks: Object Types
The core building block is the object type, declared with the type keyword. Like a class, it represents a kind of object you can fetch.
type User {
# Fields will go here
}Adding Fields with Scalar Types
Fields hold data via built-in scalar types: String, Int, Float, Boolean, and ID for unique identifiers.
type User {
id: ID
name: String
age: Int
isActive: Boolean
rating: Float
}Essential Data: Non-Null Fields
Add ! after a type to make a field non-null — it must always have a value. Query it and the server must return one or it errors.
type Product {
id: ID!
name: String!
price: Float!
description: String
}Collections: Lists in GraphQL
Wrap a type in [] for a list. Stack the ! too: [String!]! means a non-null list of non-null strings.
type Book {
id: ID!
title: String!
pages: Int
}
type Author {
id: ID!
name: String!
books: [Book] # A list of books, can be empty or null
tags: [String!]! # A list of non-null strings, and the list itself is non-null
}Entry Point: The Query Type
Every schema needs the root Query type — it defines all the entry points for clients to read data. Queries always start here.
type Query {
# Query fields will go here
}Defining Query Fields
Fields on Query are the data you can fetch, and they take arguments to filter — like book(id: ID!): Book to grab one book by id.
type Author {
id: ID!
name: String!
}
type Book {
id: ID!
title: String!
}
type Query {
allAuthors: [Author!]!
bookById(id: ID!): Book
}Your First Complete Schema
Here it all comes together: Author and Book types, a Query entry point, and a Book.author field that links the two. Relationships!
type Author {
id: ID!
name: String!
books: [Book!]! # An author has a list of non-null books
}
type Book {
id: ID!
title: String!
pages: Int
author: Author # A book has one author
}
type Query {
allBooks: [Book!]!
book(id: ID!): Book
allAuthors: [Author!]!
author(id: ID!): Author
}Schema Check-up
What does ! mean, and where does Query fit? Prove it.
Schema Design Recap
You designed a real schema: object types with the type keyword, scalar fields, ! for non-null, [] for lists, and Query as the read entry point.
Часто задаваемые вопросы
Урок «Проектирование первой схемы GraphQL» бесплатный?
Да — полный текст урока «Проектирование первой схемы GraphQL» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс GraphQL APIs with Spring Boot, подпишись на CoddyKit PRO. Курс GraphQL APIs with Spring Boot содержит 4 уроков всего.
Чему я научусь в уроке «Проектирование первой схемы GraphQL»?
Научитесь определять основные типы схемы и поля, а также разберитесь с языком определения схемы (SDL). Ты практикуешь GraphQL APIs with Spring Boot с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать GraphQL APIs with Spring Boot?
Предыдущий опыт не требуется. GraphQL APIs with Spring Boot на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 3 из 4.
Сколько времени занимает урок «Проектирование первой схемы GraphQL»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке GraphQL APIs with Spring Boot?
Да. Каждый урок GraphQL APIs with Spring Boot включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Что такое GraphQL?
- Настройка Spring Boot для GraphQL
- Проектирование первой схемы GraphQL
- GraphQL и REST: выбор правильного подхода