ASP.NET - GraphQL API Development with ASP.NET Core

Introduction

GraphQL is a modern API query language developed by Facebook that provides a more flexible and efficient way for clients to request data from a server. Unlike traditional REST APIs, where each endpoint returns a fixed set of data, GraphQL allows clients to specify exactly what information they need in a single request. This reduces unnecessary data transfer and minimizes the number of API calls required to build modern web and mobile applications.

ASP.NET Core provides excellent support for GraphQL through libraries such as Hot Chocolate and GraphQL.NET. These libraries make it easy to create GraphQL APIs that are fast, scalable, and easy to maintain. GraphQL is widely used in applications that require flexible data retrieval, such as social media platforms, e-commerce websites, dashboards, and mobile applications.


Why GraphQL Instead of REST?

REST APIs expose multiple endpoints for different resources. For example:

  • /api/products

  • /api/customers

  • /api/orders

If a client needs customer information along with their orders, it may have to call multiple endpoints.

GraphQL solves this problem by providing a single endpoint where clients define exactly which fields they need.

Example request:

query {
  customer(id: 1) {
    name
    email
    orders {
      orderId
      totalAmount
    }
  }
}

The server returns only the requested data.


Benefits of GraphQL

1. Fetch Only Required Data

GraphQL eliminates unnecessary data transfer by allowing clients to request only the required fields.

For example, instead of retrieving an entire product object containing 20 properties, the client may request only:

  • Product Name

  • Price

  • Rating

This improves application performance.


2. Single Endpoint

Unlike REST APIs that use multiple endpoints, GraphQL typically uses one endpoint.

Example:

https://example.com/graphql

All queries, mutations, and subscriptions are processed through this endpoint.


3. Reduced Network Requests

Instead of sending several HTTP requests, GraphQL combines related data into a single query.

Example:

Instead of requesting:

  • Customer

  • Orders

  • Payments

individually, GraphQL retrieves everything in one request.


4. Strongly Typed Schema

GraphQL APIs define every object, field, and relationship inside a schema.

This schema acts as a contract between the client and server.

Benefits include:

  • Better documentation

  • Easier development

  • Automatic validation

  • Improved code completion


5. Better Performance

Since clients retrieve only necessary data:

  • Response size becomes smaller.

  • Bandwidth usage decreases.

  • Mobile applications become faster.

  • Server resources are utilized efficiently.


Installing GraphQL in ASP.NET Core

One popular library is Hot Chocolate.

Install the package:

dotnet add package HotChocolate.AspNetCore

Another useful package:

dotnet add package HotChocolate.Data

These packages provide GraphQL server functionality.


Configuring GraphQL

Inside Program.cs

var builder = WebApplication.CreateBuilder(args);

builder.Services
.AddGraphQLServer()
.AddQueryType<Query>();

var app = builder.Build();

app.MapGraphQL();

app.Run();

This configuration creates the GraphQL server.


Creating a GraphQL Model

Example Product model:

public class Product
{
    public int Id { get; set; }

    public string Name { get; set; }

    public decimal Price { get; set; }

    public string Category { get; set; }
}

This model represents product information.


Creating a Query Class

GraphQL retrieves data through Query classes.

Example:

public class Query
{
    public List<Product> GetProducts()
    {
        return new List<Product>
        {
            new Product
            {
                Id = 1,
                Name = "Laptop",
                Price = 60000,
                Category = "Electronics"
            },

            new Product
            {
                Id = 2,
                Name = "Keyboard",
                Price = 1500,
                Category = "Accessories"
            }
        };
    }
}

This method returns product data.


Executing a GraphQL Query

A client can send:

query
{
  products
  {
    id
    name
    price
  }
}

Response:

{
  "data": {
    "products": [
      {
        "id":1,
        "name":"Laptop",
        "price":60000
      },
      {
        "id":2,
        "name":"Keyboard",
        "price":1500
      }
    ]
  }
}

Notice that only the requested fields are returned.


Query Arguments

GraphQL supports filtering using parameters.

Example:

query
{
  product(id:1)
  {
    id
    name
    price
  }
}

Corresponding method:

public Product GetProduct(int id)
{
    return products.FirstOrDefault(p => p.Id == id);
}

Nested Queries

GraphQL can retrieve related objects.

Example:

query
{
  customer(id:1)
  {
    name

    orders
    {
      orderId
      total
    }
  }
}

The server automatically retrieves related data.


Mutations

Queries retrieve data.

Mutations modify data.

Examples include:

  • Insert

  • Update

  • Delete

Mutation example:

mutation
{
  addProduct(
    name:"Mouse",
    price:800
  )
  {
    id
    name
  }
}

Corresponding C# code:

public Product AddProduct(string name, decimal price)
{
    Product product = new Product
    {
        Id = 3,
        Name = name,
        Price = price
    };

    return product;
}

Updating Data

Example mutation:

mutation
{
  updateProduct(
    id:2,
    price:1800
  )
  {
    id
    name
    price
  }
}

This updates an existing product.


Deleting Data

Example:

mutation
{
  deleteProduct(id:2)
}

The server removes the specified record.


GraphQL Subscriptions

Subscriptions enable real-time communication between the server and clients. Instead of repeatedly sending requests to check for updates, the server automatically pushes new information whenever specific events occur.

Example use cases include:

  • Live chat applications

  • Stock market updates

  • Sports score updates

  • Online gaming

  • Order tracking

  • Notification systems

Subscription example:

subscription
{
  productAdded
  {
    id
    name
    price
  }
}

Whenever a new product is added, subscribed clients receive the updated information automatically.


GraphQL Schema

The schema defines the structure of the API.

Example:

type Product
{
    id: Int!

    name: String!

    price: Float!

    category: String
}

The schema specifies available fields and their data types.


Error Handling

GraphQL returns structured error information instead of generic HTTP errors.

Example response:

{
  "errors":[
    {
      "message":"Product not found"
    }
  ]
}

This makes debugging easier for developers.


Authentication and Authorization

GraphQL APIs can be secured using ASP.NET Core authentication mechanisms such as:

  • JWT Authentication

  • OAuth 2.0

  • OpenID Connect

  • Cookie Authentication

Role-based authorization can also be applied to restrict access to specific queries or mutations.

Example:

[Authorize]
public List<Product> GetProducts()
{
    return products;
}

Only authenticated users can access this query.


Pagination

Large datasets can be divided into smaller pages for improved performance.

Example:

query
{
  products(
    first:10
  )
  {
    name
    price
  }
}

Pagination reduces response size and speeds up data retrieval.


Filtering and Sorting

GraphQL supports filtering records based on conditions and sorting them in different orders.

Example:

query
{
  products(
    where:
    {
      category:
      {
        eq:"Electronics"
      }
    }
  )
  {
    name
    price
  }
}

Sorting example:

query
{
  products(
    order:
    {
      price: DESC
    }
  )
  {
    name
    price
  }
}

These features simplify querying large datasets.


Best Practices

  • Design a clear and well-organized schema with meaningful object types and field names.

  • Use pagination for queries that return large collections of data.

  • Apply filtering and sorting to reduce unnecessary data transfer.

  • Secure APIs using authentication and authorization.

  • Validate input data before processing mutations.

  • Handle errors gracefully with descriptive messages.

  • Enable query complexity analysis to prevent expensive or malicious queries.

  • Use DataLoader or similar batching techniques to avoid redundant database calls.

  • Document the schema and keep it version-aware if significant changes are introduced.

  • Monitor performance and optimize database access to ensure efficient query execution.


Real-World Applications

GraphQL with ASP.NET Core is commonly used in:

  • E-commerce platforms for retrieving product catalogs, customer profiles, and order details.

  • Social networking applications where users, posts, comments, and reactions are interconnected.

  • Financial dashboards that combine account, transaction, and investment data into a single response.

  • Healthcare systems for securely accessing patient records, appointments, and medical histories.

  • Learning Management Systems (LMS) for managing courses, students, instructors, assignments, and grades.

  • Content Management Systems (CMS) for efficiently serving articles, media, and metadata to websites and mobile applications.

  • Travel and booking platforms for fetching flights, hotels, reservations, and user preferences in one request.

GraphQL API development with ASP.NET Core enables developers to build flexible, efficient, and scalable APIs that meet the needs of modern applications. By supporting precise data retrieval, strongly typed schemas, real-time subscriptions, and robust tooling, GraphQL offers significant advantages over traditional REST APIs, especially for applications with complex data relationships and multiple client platforms.