graphql 教程


GraphQL vs REST: 一个小案例

rest api vs graphql

grahpql example

a graphql query

operation types

schema's types

GraphQL schema defines what types of data a client can read and write to your data graph

type Launch {
id: ID!
site: String
mission: Mission
rocket: Rocket
isBooked: Boolean!

The Launch object type has a collection of fields, and each field has a type of its own. A field's type can be either an object type or a scalar type. A scalar type is a primitive (like ID, String, Boolean, or Int) that resolves to a single value. In addition to GraphQL's built-in scalar types, you can define custom scalar types.

An exclamation point (!) after a declared field's type means "this field's value can never be null."

type User {
id: ID!
email: String!
trips: [Launch]!

If a declared field's type is in [Square Brackets], it's an array of the specified type. If an array has an exclamation point after it, the array cannot be null, but it can be empty.

type Mission {
name: String
missionPatch(size: PatchSize): String
enum PatchSize {

The missionPatch field of the Mission type takes an argument named size, which is of the enum type PatchSize. When you query for a field that takes an argument, the field's value can vary depending on the provided argument's value. In this case, the value you provide for size will determine which size of the mission's associated patch is returned (the SMALL size or the LARGE size).

The Query type

our schema needs to define queries that clients can execute against the data graph

You define your data graph's supported queries as fields of a special type called the Query type

type Query {
launches: [Launch]!
launch(id: ID!): Launch
me: User

This Query type defines three available queries for clients to execute: launches, launch, and me.

The Mutation type

Queries enable clients to fetch data, but not to modify data. To enable clients to modify data, our schema needs to define some mutations.

The Mutation type is a special type that's similar in structure to the Query type.

type Mutation {
bookTrips(launchIds: [ID]!): TripUpdateResponse!
cancelTrip(launchId: ID!): TripUpdateResponse!
login(email: String): String # login token