Bun + GraphQL API
×


Bun + GraphQL API

108

🧬 Introduction to Bun + GraphQL API

GraphQL has become the go-to choice for building flexible and efficient APIs, and Bun is rapidly emerging as the fastest JavaScript runtime in the modern dev stack. Combining both gives you a lightning-fast backend with query precision.⚡️💡

In this guide, we’ll walk through setting up a GraphQL API using Bun, from schema to server, and show how to make it blazing-fast and production-ready.

📚 Why Use GraphQL with Bun?

Traditional REST APIs can be rigid — you're either under-fetching or over-fetching. GraphQL lets clients ask for exactly what they need. Now mix that with Bun’s speed and low resource usage, and you’ve got:

  • 🚀 Super-fast API responses
  • 🧠 Flexible data querying
  • 💾 Lower server footprint
  • 🔧 Easy integration with modern tools

🔧 Setting Up Bun for GraphQL

Let’s start by creating a new Bun project and installing GraphQL dependencies.

bun init graphql-api
cd graphql-api
bun add graphql

You can also use libraries like graphql-yoga or apollo-server if you need advanced tooling, but here we’ll keep it simple and use the raw graphql module for clarity.

📐 Creating a GraphQL Schema

First, define a schema using the GraphQL schema language:

import { buildSchema } from "graphql";

const schema = buildSchema(`
  type Query {
    hello: String
    user(id: ID!): User
  }

  type User {
    id: ID
    name: String
    email: String
  }
`);

🧠 Defining Resolvers

Resolvers provide the actual logic for fetching data. Here’s how to implement a simple one:

const fakeUsers = [
  { id: "1", name: "Alice", email: "alice@example.com" },
  { id: "2", name: "Bob", email: "bob@example.com" }
];

const root = {
  hello: () => "Hello from Bun + GraphQL 👋",
  user: ({ id }) => fakeUsers.find(user => user.id === id)
};

🚀 Setting Up the Server with Bun

Bun’s fetch-based server makes it easy to run a GraphQL endpoint:

import { graphql } from "graphql";

Bun.serve({
  port: 3000,
  fetch: async (req) => {
    if (req.method === "POST") {
      const { query, variables } = await req.json();
      const result = await graphql({
        schema,
        source: query,
        rootValue: root,
        variableValues: variables
      });

      return new Response(JSON.stringify(result), {
        headers: { "Content-Type": "application/json" }
      });
    }

    return new Response("GraphQL API is running 🚀");
  }
});

🧪 Testing Your GraphQL Endpoint

Use curl, Postman, or GraphQL Playground to run queries like:

{
  hello
}

Or fetch a specific user:

{
  user(id: "1") {
    name
    email
  }
}

If everything’s working, your Bun-powered GraphQL API will respond almost instantly ⚡.

🔐 Handling Errors Gracefully

GraphQL makes error handling structured by default. But you can customize your logic too:

const root = {
  user: ({ id }) => {
    const found = fakeUsers.find(user => user.id === id);
    if (!found) throw new Error("User not found");
    return found;
  }
};

This will return errors in the response payload while maintaining HTTP 200 OK.

🎁 Bonus: Adding Mutations

Let’s add a mutation to create a new user:

const schema = buildSchema(`
  type Query {
    hello: String
    user(id: ID!): User
  }

  type Mutation {
    createUser(name: String!, email: String!): User
  }

  type User {
    id: ID
    name: String
    email: String
  }
`);

let users = [...fakeUsers];

const root = {
  createUser: ({ name, email }) => {
    const newUser = {
      id: String(users.length + 1),
      name,
      email
    };
    users.push(newUser);
    return newUser;
  }
};

Now you can send POST requests with GraphQL mutation queries to add data. ✅

📦 Production Tips

  • 🔒 Add authentication middleware for protected queries
  • 📉 Use caching strategies for heavy queries
  • 📈 Monitor with logging and metrics
  • 📂 Break schema and resolvers into modules as the app scales

🏁 Final Thoughts

Combining Bun + GraphQL gives you the best of both worlds: the speed and simplicity of Bun with the flexibility of GraphQL. Whether you're building microservices, mobile backends, or SaaS platforms — this combo is lean, modern, and future-ready 🚀💪.



If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!

For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!


Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments

Coding Tag WhatsApp Chat