GraphQL API mit C#: Schritt-für-Schritt-Tutorial in der Praxis

Online Python-Trainer für Anfänger

Lernen Sie Python einfach ohne theoretische Überlastung. Lösen Sie praktische Aufgaben mit automatischer Überprüfung und schreiben Sie Code direkt im Browser.

Kurs starten

GraphQL API mit C#: Schritt-für-Schritt-Tutorial in der Praxis



In der modernen Webentwicklung wird GraphQL zunehmend zu einer beliebten Alternative zu REST APIs. Im Gegensatz zu REST, wo jeder Endpunkt eine feste Datenstruktur zurückgibt, ermöglicht GraphQL dem Client, genau die Daten anzufordern, die er benötigt. In diesem Tutorial erstellen wir eine vollwertige GraphQL API mit C# (.NET) unter Verwendung der Bibliothek Hot Chocolate. Sie erfahren, wie Sie den Server einrichten, Datentypen definieren, Abfragen und Mutationen implementieren sowie Abonnements für Echtzeit-Updates hinzufügen.



Was ist GraphQL und warum sollte man es mit C# verwenden?



GraphQL ist eine Abfragesprache für APIs, die von Facebook entwickelt wurde. Die Hauptvorteile:

  • Flexibilität der Abfragen — der Client entscheidet selbst, welche Felder abgerufen werden
  • Einheitlicher Einstiegspunkt — ein Endpunkt für alle Abfragen
  • Starke Typisierung — alle Datentypen sind streng definiert
  • Kein Over-fetching und Under-fetching — Sie erhalten genau das, was Sie angefordert haben

Im .NET-Ökosystem ist die beste Bibliothek zur Implementierung von GraphQL Hot Chocolate. Sie unterstützt alle Funktionen der GraphQL-Spezifikation, einschließlich Abfragen (queries), Mutationen (mutations) und Abonnements (subscriptions).



Projektvorbereitung und Installation von Abhängigkeiten



Beginnen wir mit der Erstellung eines neuen ASP.NET Core-Projekts. Öffnen Sie das Terminal oder die Eingabeaufforderung und führen Sie Folgendes aus:

dotnet new webapi -n GraphQLDemocd GraphQLDemo


Jetzt installieren wir das Paket Hot Chocolate:

dotnet add package HotChocolate.AspNetCoredotnet add package HotChocolate.AspNetCore.Playground


Erstellen wir ein Datenmodell für unsere API. Nehmen wir an, wir arbeiten mit Büchern und Autoren. Erstellen Sie einen Ordner Models und fügen Sie die folgenden Klassen hinzu:



// Models/Author.cspublic class Author{    public int Id { get; set; }    public string Name { get; set; }    public ICollection<Book> Books { get; set; }}

// Models/Book.cspublic class Book{ public int Id { get; set; } public string Title { get; set; } public int AuthorId { get; set; } public Author Author { get; set; }}


Erstellung des GraphQL-Schemas und der Resolver



In GraphQL sind die Schlüsselkomponenten Typen, Abfragen (Query) und Mutationen (Mutation). Erstellen Sie einen Ordner GraphQL und fügen Sie die folgenden Dateien hinzu:



// GraphQL/Query.cspublic class Query{    public IQueryable<Book> GetBooks([Service] ApplicationDbContext context)    {        return context.Books.Include(b => b.Author);    }

public Book GetBook(int id, [Service] ApplicationDbContext context) { return context.Books.Include(b => b.Author).FirstOrDefault(b => b.Id == id); }

public IQueryable<Author> GetAuthors([Service] ApplicationDbContext context) { return context.Authors.Include(a => a.Books); }}

// GraphQL/Mutation.cspublic class Mutation{ public async Task<Book> AddBook(string title, int authorId, [Service] ApplicationDbContext context) { var book = new Book { Title = title, AuthorId = authorId }; context.Books.Add(book); await context.SaveChangesAsync(); return book; }

public async Task<Author> AddAuthor(string name, [Service] ApplicationDbContext context) { var author = new Author { Name = name }; context.Authors.Add(author); await context.SaveChangesAsync(); return author; }}


Jetzt registrieren wir diese Klassen in Program.cs:



// Program.csvar builder = WebApplication.CreateBuilder(args);

builder.Services .AddDbContext<ApplicationDbContext>(options => options.U

Blogs

Buchempfehlungen