Read on Medium: From REST to GraphQL: Why It Might Be Time to Switch
From REST to GraphQL: Why It Might Be Time to Switch
Are you tired of over-fetching or under-fetching data from your REST APIs?
You’re not alone. REST has been the go-to standard for years, but with modern frontend needs getting more complex, it’s starting to show its limits.
That’s where GraphQL steps in.
In this beginner-friendly guide, we’ll break down what GraphQL is, how it compares to REST, and walk through real-world examples to show why many developers are making the switch.
What is GraphQL?
GraphQL is a query language for your API, developed by Facebook. Unlike REST, which exposes multiple endpoints for different resources, GraphQL exposes just one endpoint and allows clients to ask exactly for the data they need — nothing more, nothing less.
🧠 Core Concepts of GraphQL
- Schema: Defines types and relationships in your API.
- Query: Read-only operation to fetch data.
- Mutation: Write or update operation.
- Resolver: Functions that return data for fields in the schema.
🆚 REST vs GraphQL — Real Example
REST (Over-fetching Example)
GET /users/1
GET /users/1/postsYou hit two endpoints, and you might receive unnecessary fields in both.
query {
user(id: 1) {
name
posts {
title
content
}
}
}
You get exactly what you ask for — no more, no less.
Let’s create a simple GraphQL server using Node.js and Apollo.
Step 1: Initialize Project
npm install apollo-server graphqlStep 2: Create index.js
```// Type definitions (schema)
const typeDefs = gql`
type User {
id: ID!
name: String!
email: String!
}
type Query {
users: [User]
}
`;
// Dummy data
const users = [
{ id: 1, name: "Alice", email: "alice@mail.com" },
{ id: 2, name: "Bob", email: "bob@mail.com" }
];
// Resolvers
const resolvers = {
Query: {
users: () => users,
},
};
// Create server
const server = new ApolloServer({ typeDefs, resolvers });
// Run server
server.listen().then(({ url }) => {
console.log(`Server ready at ${url}`);
});Step 3: Test Your API Run the server:
Now go to the provided URL and run this GraphQL query:
query {
users {
name
email
}
}
---
## Final Thoughts
GraphQL isn’t here to kill REST. It’s here to solve modern pain points like nested data fetching and reducing the number of API calls needed.
Try converting a small part of your existing REST API to GraphQL and experience the flexibility yourself.
## Call to Action
GraphQL might seem intimidating at first, but with a little practice, it unlocks a powerful new way to build APIs.
---