0Pricing
Node.js Backend Development Bootcamp · Lección

Principios de diseño de API GraphQL

Aprenda los fundamentos de GraphQL, incluidos esquemas, consultas, mutaciones y suscripciones, para diseñar API flexibles.

Principios de diseño de API GraphQL es una lección gratuita de Node.js Backend Development Bootcamp en CoddyKit. Esta es la lección 2 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Node.js Backend Development Bootcamp, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Node.js Backend Development Bootcamp incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

What is GraphQL?

Welcome to GraphQL API Design! GraphQL is a powerful query language for your APIs and a runtime for fulfilling those queries with your existing data.

Think of it as a way for clients (like your mobile app) to ask for exactly the data they need, no more, no less. It's an alternative to traditional REST APIs.

Principios de diseño de API GraphQL — ilustración 1

GraphQL vs. REST APIs

While REST APIs typically have multiple endpoints, each returning a fixed data structure, GraphQL uses a single endpoint.

  • REST: Often leads to over-fetching (getting more data than needed) or under-fetching (needing multiple requests for related data).
  • GraphQL: Solves this by allowing clients to specify the data shape, reducing network requests and improving efficiency.

The Core: GraphQL Schema

At the heart of every GraphQL API is its schema. The schema defines the entire API's capabilities: what data can be queried, what data can be modified, and what types of data exist.

It acts as a contract between the client and the server, ensuring both sides understand the available operations and data structures.

Schema Definition Language (SDL)

GraphQL schemas are written using the Schema Definition Language (SDL). It's a simple, intuitive language for defining types and operations.

Let's look at a basic example of defining a User type with some fields:

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

Understanding SDL Types

In the previous example:

  • type User: Defines a new object type named User.
  • id: ID!: id is a field of type ID. The ! means it's non-nullable (always present).
  • String, Int, ID: These are scalar types, GraphQL's built-in basic data types.
  • You can also define custom object types like Post or Comment.

Root Type: Query

The Query root type is special. It defines all the entry points for reading data from your API. Think of these as the 'GET' operations in REST.

Here's how you might add operations to fetch users or a single user by ID:

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

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

Executing a GraphQL Query

Once the Query type is defined, clients can request data. They specify which fields they want from the available operations. This is how you avoid over-fetching!

To get all user names and IDs:

query GetUsers {
  users {
    id
    name
  }
}

Root Type: Mutation

The Mutation root type defines all the entry points for writing or changing data in your API. These are like 'POST', 'PUT', 'PATCH', and 'DELETE' operations in REST.

Mutations often take input arguments and return the modified object.

type Mutation {
  createUser(name: String!, email: String, age: Int): User!
  updateUser(id: ID!, name: String, email: String, age: Int): User
  deleteUser(id: ID!): Boolean!
}

Executing a GraphQL Mutation

Similar to queries, clients send mutations to perform data modifications. They specify the mutation name, its arguments, and what fields of the result they want back.

Here's an example to create a new user:

mutation CreateNewUser {
  createUser(name: "Alice", email: "alice@example.com", age: 30) {
    id
    name
    email
  }
}

Schema Design Quick Check

Consider the following GraphQL schema snippet. Which statements about it are TRUE?

type Book {
  id: ID!
  title: String!
  author: Author!
}

type Author {
  id: ID!
  name: String!
  books: [Book!]
}

type Query {
  books: [Book!]!
  book(id: ID!): Book
  authors: [Author!]!
}

type Mutation {
  createBook(title: String!, authorId: ID!): Book!
}

Recap & Beyond

Great job! You've learned the core principles of GraphQL API design:

  • GraphQL allows clients to request specific data.
  • The Schema Definition Language (SDL) defines the API's contract.
  • Object types define data structures.
  • The Query root type handles data fetching.
  • The Mutation root type handles data modification.

Next, we'll dive into building a GraphQL server with Apollo to bring these designs to life!

Preguntas frecuentes

¿La lección «Principios de diseño de API GraphQL» es gratis?

Sí — el texto completo de «Principios de diseño de API GraphQL» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Node.js Backend Development Bootcamp, actualiza a CoddyKit PRO. El curso de Node.js Backend Development Bootcamp incluye 4 lecciones en total.

¿Qué aprenderé en «Principios de diseño de API GraphQL»?

Aprenda los fundamentos de GraphQL, incluidos esquemas, consultas, mutaciones y suscripciones, para diseñar API flexibles. Practicas Node.js Backend Development Bootcamp con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Node.js Backend Development Bootcamp?

No se requiere experiencia previa. Node.js Backend Development Bootcamp en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 2 de 4.

¿Cuánto tiempo toma la lección «Principios de diseño de API GraphQL»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Node.js Backend Development Bootcamp?

Sí. Cada lección de Node.js Backend Development Bootcamp incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Introducción al serverless con Node.js
  2. Principios de diseño de API GraphQL
  3. Creación de un servidor GraphQL con Apollo
  4. Suscripciones de GraphQL para datos en tiempo real
← Volver a Node.js Backend Development Bootcamp