Skip to content
Tutorials Center
My learning

Topics

Lesson 146 of 182 ยท ASP.NET Core

OpenAPI Docs and GraphQL

Document ASP.NET Core APIs with OpenAPI and Swagger UI, then learn how GraphQL works - schemas, queries, resolvers, the N+1 problem and Hot Chocolate - with a runnable mini OpenAPI generator and GraphQL engine.

An API is only as useful as it is understandable. A mobile team in another city must know which URLs exist, which parameters they take and what comes back, without reading your source code or interrupting you on chat. Two technologies solve this problem in different ways. OpenAPI (the standard formerly called Swagger) describes an ordinary HTTP API in a machine-readable file, from which documentation sites, client libraries and tests are generated. GraphQL changes the API style: instead of many fixed endpoints, there is one endpoint and a typed schema, and clients ask for exactly the fields they need.

This lesson covers both for ASP.NET Core. Each real library (Microsoft.AspNetCore.OpenApi, Swagger UI, Hot Chocolate) is a NuGet package, which our single-file runner cannot download, so the package-based code is shown read-only. But the ideas are small enough to implement: you will build a mini OpenAPI generator that reads endpoint metadata and reflection, and a mini GraphQL engine with a parser, resolvers and the famous N+1 problem. That way you know exactly what the libraries do for you. You should be comfortable with minimal APIs, API design (which introduced OpenAPI metadata) and reflection.

OpenAPI: a contract for HTTP APIs

An OpenAPI document is a JSON (or YAML) file with a fixed structure:

Section Describes
info title, version, description of the API
servers base URLs
paths each URL, and under it each HTTP method (an operation)
operation: operationId, tags, summary a unique name (client generators turn it into a method name), grouping, a one-line description
operation: parameters inputs from the path, query string or headers, with types and whether they are required
operation: requestBody the body the client must send, with a content type and a schema
operation: responses per status code, what the response means and its body schema
components.schemas reusable JSON Schema definitions of your types, referenced with $ref
components.securitySchemes how to authenticate (bearer token, API key, OAuth)

The document is a contract. Anything that understands OpenAPI can use it:

flowchart LR
    C["C# endpoints<br/>+ metadata"] --> G["OpenAPI generator"]
    G --> D["openapi.json"]
    D --> U["Documentation UI<br/>(Swagger UI, Scalar)"]
    D --> K["Client generators<br/>(Kiota, NSwag)"]
    D --> T["Contract tests,<br/>mock servers, linters"]
    D --> A["API gateways"]

One generated document feeds documentation, typed clients in many languages, tests and gateways.

The real setup in ASP.NET Core

Since .NET 9, document generation is a first-party package, Microsoft.AspNetCore.OpenApi. The generator inspects each endpoint's metadata (route, HTTP method, parameter types, Produces declarations, WithName, WithTags, summaries) and the .NET types involved. Shown read-only:

C#
// Read-only: needs the NuGet package Microsoft.AspNetCore.OpenApi
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddOpenApi(options =>
{
    // A document transformer can edit the finished document: title, servers, security, ...
    options.AddDocumentTransformer((document, context, cancellationToken) =>
    {
        document.Info.Title = "Shop API";
        document.Info.Version = "v1";
        return Task.CompletedTask;
    });
});

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.MapOpenApi();                 // serves the document at /openapi/v1.json
}

You can also generate the file at build time (the Microsoft.Extensions.ApiDescription.Server package) and commit or publish it, which is how teams catch accidental breaking changes: the document is diffed in code review or checked in CI by a tool such as oasdiff. Recent versions also read your /// XML documentation comments into summaries and descriptions when GenerateDocumentationFile is enabled, so writing good comments documents the API as a side effect.

A documentation UI is a separate package that loads that JSON in the browser and lets people read and try the endpoints. The two common choices:

C#
// Read-only: Swagger UI (Swashbuckle.AspNetCore.SwaggerUI package)
app.UseSwaggerUI(options => options.SwaggerEndpoint("/openapi/v1.json", "Shop API v1"));

// Read-only: Scalar (Scalar.AspNetCore package), a modern alternative
app.MapScalarApiReference();

(Swashbuckle.AspNetCore and NSwag are older, full-featured libraries that generate the document and host the UI; many existing projects still use them.)

Your API document is a map of your attack surface. Publish the interactive UI in development and staging, and think carefully before exposing it in production. If you do publish it, keep internal and admin endpoints out of it (ExcludeFromDescription()), and never put real secrets, tokens or production URLs in examples.

Building an OpenAPI generator

To understand what the package does, the program below builds a small generator. It walks the endpoints, reads the same metadata the real generator reads, uses reflection on the handler's parameters to find path/query/body inputs, converts C# types to JSON Schema (registering complex types under components.schemas), and prints a valid-shaped document. It then serves the document from /openapi.json and consumes it like a client generator would, printing a typed method list.

C# A mini OpenAPI generator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Study the output top to bottom. Route constraints like :int are gone from the path template, because OpenAPI describes them with a schema. id is a required path parameter; category is an optional query parameter because its type is string? (nullability annotations become "required" flags); page is optional because it has a default. The NewProduct parameter, which is not a simple type or a route value, became the request body. Product appears once under components.schemas and is referenced with $ref from three places; Category is missing from its required list because it is string?. Finally, the generated "client" shows why WithName matters: operationId is literally the method name. Real generators handle far more (enums, inheritance, polymorphism, validation attributes, authentication, XML comments, versioned documents), but this is the core.

Good OpenAPI hygiene is mostly metadata discipline: stable WithNames, WithTags for grouping, Produces for every status your endpoint can return (including errors), WithSummary and WithDescription, and separate request and response record types. Treat the document as part of your public API and review changes to it as carefully as changes to code.

GraphQL: ask for exactly what you need

REST gives you many endpoints, each returning a fixed shape. That causes two classic complaints. Over-fetching: GET /products/7 returns twenty fields when the screen needs two. Under-fetching: showing a product with its reviews and author needs three requests. GraphQL is a query language and runtime that fixes both by turning the API inside out:

  • There is one endpoint (usually POST /graphql).
  • The server publishes a typed schema: the types, their fields, and the entry points.
  • The client sends a query that names exactly the fields it wants, nested as deep as needed, and gets back JSON with the same shape.
sequenceDiagram
    participant App as Client app
    participant S as GraphQL endpoint
    participant R as Resolvers
    participant DB as Database
    App->>S: POST /graphql { books { title author { name } } }
    S->>S: parse + validate against the schema
    S->>R: resolve books
    R->>DB: load books
    loop for each book
        S->>R: resolve author (only if requested)
        R->>DB: load author
    end
    S-->>App: { "data": { "books": [ { "title": "...", "author": { "name": "..." } } ] } }

The server executes only the fields in the query; each field is produced by a small function called a resolver.

A schema is written in SDL (schema definition language), for example:

TEXT
type Query {
  book(id: Int!): Book
  books(author: String): [Book!]!
}

type Book {
  id: Int!
  title: String!
  year: Int!
  author: Author!
}

type Author {
  id: Int!
  name: String!
}

! means non-null, [Book!]! is a non-null list of non-null books. There are three operation types: query (read), mutation (write) and subscription (a stream of events, usually over WebSockets, see realtime and gRPC). Beyond that, GraphQL has variables (query($id: Int!)), aliases, fragments for reusing field sets, directives (@include, @skip), and introspection: clients can ask the server for its own schema, which powers tools like auto-complete editors and code generators.

REST + OpenAPI GraphQL
Endpoints many, resource-oriented one
Response shape fixed by the server chosen by the client
Typing described by OpenAPI (optional contract) built in, enforced by the schema
HTTP caching easy (GET, URL, ETag, CDN) harder (POST to one URL; needs persisted queries or client caches)
Errors HTTP status codes usually HTTP 200 with an errors array alongside partial data
Best for public APIs, simple resources, file transfer UIs that compose data from many sources, mobile apps with varied screens
Risks over/under-fetching, endpoint sprawl expensive queries, N+1 database access, harder rate limiting

Neither is "better". Many systems use both: REST for public integrations and GraphQL as the backend-for-frontend of an app.

A GraphQL engine in 150 lines

The program below implements a small subset: queries with nested selections, field arguments and aliases. It has a parser (text to a tree of fields), an executor that walks the tree and calls resolvers, and an unknown-field error. It is exposed as POST /graphql in a minimal API. Pay special attention to the counters it prints, which expose the N+1 problem.

C# A mini GraphQL engine with resolvers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The first query returned only titles; fields like year were never resolved, so the server did not even compute them. The second shows the engine following the requested shape through the object graph, and the counter exposes the cost: one author lookup per book. With 3 books that is merely 3 lookups, but a list of 1,000 books means 1,000 database queries (plus the one for the list), which is the N+1 problem. (The fourth query hides the same trap inside a resolver: it returns a single book, yet the counter says 3, because filtering by the author argument loads every book's author.) Aliases (first:, old:) let one query ask for the same field twice with different arguments. The last query fails validation with a clear message, and the HTTP status is still 200: GraphQL reports problems in an errors array, because one query can contain parts that succeed and parts that fail.

Fixing N+1: batching

The standard remedy is the DataLoader pattern. Instead of fetching an author the moment a resolver asks, the resolver registers the key with a per-request loader and gets a promise. After the current level of the query is resolved, the loader runs one batched query (WHERE id IN (1, 2)) for all collected keys and completes every waiting resolver, and it caches results, so author 1 is loaded only once even though two books share her. A simplified synchronous version, using only a per-request cache, already drops the number of lookups to the number of distinct authors:

C#
// The idea in miniature: one cache per request
var cache = new Dictionary<int, Author>();
Author LoadAuthorCached(int id)
{
    if (!cache.TryGetValue(id, out Author? author))
    {
        authorQueries++;                          // only the first time per id
        author = cache[id] = authors.Single(a => a.Id == id);
    }
    return author;
}
// { books { title author { name } } } -> 2 lookups instead of 3

Production libraries add true batching (one IN (...) query) with the GreenDonut DataLoader, or avoid the problem for database-backed data by projecting the GraphQL selection into the SQL query (Entity Framework Core Select/Include generated from the requested fields).

GraphQL in ASP.NET Core with Hot Chocolate

You rarely write a GraphQL engine yourself. In .NET the most widely used server library is Hot Chocolate (NuGet HotChocolate.AspNetCore). It follows a code-first approach: your C# classes are the schema. Read-only sample:

C#
// Read-only: needs the NuGet package HotChocolate.AspNetCore
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddDbContext<ShopDb>();
builder.Services
    .AddGraphQLServer()
    .AddQueryType<Query>()
    .AddMutationType<Mutation>()
    .AddProjections()           // translate the requested fields into a narrow SELECT
    .AddFiltering()             // where: { year: { gt: 1970 } }
    .AddSorting();              // order: { year: DESC }

var app = builder.Build();
app.MapGraphQL();               // POST /graphql, plus a built-in IDE in development
app.Run();

public class Query
{
    [UseProjection, UseFiltering, UseSorting]
    public IQueryable<Book> GetBooks(ShopDb db) => db.Books;       // field name: books
}

public class Mutation
{
    public async Task<Book> AddBook(AddBookInput input, ShopDb db)
    {
        var book = new Book { Title = input.Title, Year = input.Year, AuthorId = input.AuthorId };
        db.Books.Add(book);
        await db.SaveChangesAsync();
        return book;
    }
}

Methods and properties of your classes become schema fields (the Get prefix is dropped), parameters become arguments or injected services, Task<T> is awaited, and the C# nullability annotations (string?) turn into the GraphQL ! markers. The library handles parsing, validation, execution, introspection, subscriptions, DataLoaders, persisted queries, and authorization (the usual [Authorize] attribute works on fields). A client tool such as Strawberry Shake can generate a fully typed C# client from a schema and your .graphql query files, which is the GraphQL equivalent of the OpenAPI client generators above.

Operating a GraphQL API safely

Giving clients a query language also gives them ways to hurt you. Plan for these from the start:

  • Query cost and depth limits. A query can nest author { books { author { books ... } } } without end. Set a maximum depth, a maximum complexity score, and pagination limits on every list field.
  • Timeouts and rate limits. The single endpoint means a plain request-per-minute limit is crude; combine it with complexity scoring (see health checks and rate limiting).
  • Authorization per field and per object, not just per endpoint: the same Author type may be reachable by several paths. Use authorization policies on fields and re-check in resolvers when data depends on the user.
  • Disable or restrict introspection and the built-in IDE in production if the schema is not public.
  • Persisted queries. Let clients register known queries and call them by hash; this allows caching, shrinks requests and lets you reject unknown queries entirely.
  • Observability. Log operation names, durations and resolver timings; one slow resolver hides behind one fast HTTP endpoint otherwise.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the operationId in an OpenAPI operation used for?

    operationId uniquely names an operation. In ASP.NET Core it comes from WithName, and client generators use it for the generated method.
  2. 2. In the generated document, why does a parameter of type string? become an optional query parameter?

    Route parameters are required. For others, a nullable type or a default value marks the parameter as not required.
  3. 3. Which problem does GraphQL mainly address compared with fixed REST endpoints?

    A GraphQL client names exactly the fields it needs, even nested ones, in a single request.
  4. 4. A query asks for 500 books and each book's author. The author resolver runs one database query per book. What is this called, and what helps?

    One query for the list plus N queries for the related items is the N+1 problem. DataLoaders batch and cache lookups, and projections push the requested fields into one SQL query.
  5. 5. A GraphQL query refers to a field that does not exist. What does a typical GraphQL server return?

    GraphQL reports errors in the response body, so it can return partial data together with errors. The HTTP status is normally 200 for executed operations.

Summary

  • OpenAPI is a machine-readable contract for HTTP APIs: paths, operations, parameters, request bodies, responses and shared schemas. It feeds documentation UIs, client generators and tests.
  • In ASP.NET Core, Microsoft.AspNetCore.OpenApi generates the document from endpoint metadata (WithName, WithTags, Produces, parameter types); invest in that metadata and review document changes like code changes.
  • GraphQL has one endpoint and a typed schema; clients select exactly the fields they need, and each field is produced by a resolver.
  • Naive resolvers cause the N+1 problem; use batching and caching (DataLoader) or projections.
  • Hot Chocolate turns C# classes into a GraphQL schema; protect GraphQL APIs with depth and cost limits, field-level authorization and persisted queries.
  • REST with OpenAPI and GraphQL are complementary, not rivals.

Next: Data Access in .NET