Databases store and organize data safely. GraphQL helps apps ask for just the data they need from databases quickly and clearly.
Why databases back 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.
{
getUser(id: "123") {
name
email
}
}{
getUser(id: "123") {
id
}
}{
getUser(id: "999") {
name
}
}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 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)
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.
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.