0
0
GraphQLquery~5 mins

Why databases back GraphQL

Choose your learning style9 modes available
Introduction

Databases store and organize data safely. GraphQL helps apps ask for just the data they need from databases quickly and clearly.

When building apps that need to get specific pieces of data from a database without extra information.
When you want to let users ask for different data shapes without changing the backend.
When you want to combine data from multiple database tables or sources in one request.
When you want to improve app speed by reducing the amount of data sent over the network.
When you want a clear way to describe what data your app can get from the database.
Syntax
GraphQL
type Query {
  getUser(id: ID!): User
}

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

This is a simple GraphQL schema defining how to ask for user data from a database.

The Query type shows what data can be requested, and the User type defines the shape of user data.

Examples
This query asks for the name and email of the user with ID 123.
GraphQL
{
  getUser(id: "123") {
    name
    email
  }
}
This query asks only for the user ID, showing you can request just what you need.
GraphQL
{
  getUser(id: "123") {
    id
  }
}
If the user with ID 999 does not exist in the database, the result will be null or an error.
GraphQL
{
  getUser(id: "999") {
    name
  }
}
Sample Program

This example shows how a GraphQL query asks for specific user data from a database. The database is simulated with a dictionary. The query asks for user with ID 1, and the program returns only the requested fields.

GraphQL
# GraphQL schema and example query

# Schema defines how to get user data
schema = '''
  type Query {
    getUser(id: ID!): User
  }

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

# Example query asking for user name and email
query = '''
{
  getUser(id: "1") {
    name
    email
  }
}
'''

# Simulated database data
users = {
  "1": {"id": "1", "name": "Alice", "email": "alice@example.com"},
  "2": {"id": "2", "name": "Bob", "email": "bob@example.com"}
}

# Simulate resolving the query
user_id = "1"
user_data = users.get(user_id)

# Output the result as GraphQL would return
result = {
  "data": {
    "getUser": {
      "name": user_data["name"],
      "email": user_data["email"]
    }
  }
}

print(result)
OutputSuccess
Important Notes

GraphQL lets clients ask for exactly the data they want, reducing extra data transfer.

Databases store the data safely and GraphQL acts as a smart middleman to get the right data.

Common mistake: expecting GraphQL to store data itself; it only queries data from databases or other sources.

Summary

Databases keep data safe and organized.

GraphQL helps apps ask for just the data they need from databases.

This makes apps faster and easier to build.