6 min read
ā¢Question 5 of 28mediumWhat is GraphQL?
Understanding GraphQL query language.
What You'll Learn
- What GraphQL is
- GraphQL vs REST
- Basic queries and mutations
What is GraphQL?
GraphQL is a query language for APIs that allows clients to request exactly the data they need.
GraphQL vs REST
| Feature | REST | GraphQL |
|---|---|---|
| Endpoints | Multiple | Single |
| Data fetching | Fixed response | Client specifies |
| Over-fetching | Common | Avoided |
| Under-fetching | Common | Avoided |
Basic Query
code.txtGRAPHQL
# Request only what you need
query {
user(id: 1) {
name
email
posts {
title
}
}
}
# Response
{
"data": {
"user": {
"name": "John",
"email": "john@example.com",
"posts": [{ "title": "My Post" }]
}
}
}Mutation Example
code.txtGRAPHQL
mutation {
createUser(input: { name: "John", email: "john@example.com" }) {
id
name
}
}Schema Definition
code.txtGRAPHQL
type User {
id: ID!
name: String!
email: String!
posts: [Post!]!
}
type Query {
user(id: ID!): User
users: [User!]!
}