Leaders Logo

API modeling with REST and GraphQL: Case study in .NET projects

Introduction to API Modeling

API modeling (Application Programming Interfaces) has become an essential practice in modern software development. APIs allow different systems to communicate with each other, enabling the integration of services and the construction of more robust and scalable applications. In this article, we will explore two popular approaches for creating APIs: REST and GraphQL, focusing on their implementations in .NET projects.

With the evolution of technologies and the growing demand for more dynamic and interactive applications, choosing the right API architecture is crucial. While REST has become a de facto standard for building APIs, GraphQL, developed by Facebook, has emerged as a powerful alternative, offering greater flexibility and efficiency in how data is retrieved.

What is REST?

REST (Representational State Transfer) is an architectural style that uses HTTP protocols for communication between client and server. RESTful APIs are built around resources, which can be represented in different formats, such as JSON or XML (LOPEZOSA SERRANO et al., 2024). The modeling of a REST API involves defining endpoints, HTTP methods (GET, POST, PUT, DELETE, etc.), and the structure of the data. REST is based on principles such as statelessness, where each client request must contain all the information necessary for the server to process the request.

One of the main benefits of REST is its simplicity and compatibility with the HTTP protocol, which is widely used and supported by virtually all platforms and programming languages. Additionally, the design of REST APIs allows developers to take advantage of response caching, improving the performance and scalability of applications (SLIWA; PANCZYK, 2021).

Implementing a REST API in .NET

To illustrate how to build a REST API in .NET, let’s consider an example of a book management system. Below, we present a basic model of a controller that exposes endpoints to manage books.


using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;

namespace BookApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class BooksController : ControllerBase
    {
        private static List<Book> books = new List<Book>()
        {
            new Book { Id = 1, Title = "1984", Author = "George Orwell" },
            new Book { Id = 2, Title = "To Kill a Mockingbird", Author = "Harper Lee" }
        };

        [HttpGet]
        public ActionResult<IEnumerable<Book>> GetBooks()
        {
            return Ok(books);
        }

        [HttpGet("{id}")]
        public ActionResult<Book> GetBook(int id)
        {
            var book = books.Find(b => b.Id == id);
            if (book == null) return NotFound();
            return Ok(book);
        }

        [HttpPost]
        public ActionResult<Book> CreateBook([FromBody] Book book)
        {
            book.Id = books.Count + 1;
            books.Add(book);
            return CreatedAtAction(nameof(GetBook), new { id = book.Id }, book);
        }

        [HttpPut("{id}")]
        public IActionResult UpdateBook(int id, [FromBody] Book updatedBook)
        {
            var book = books.Find(b => b.Id == id);
            if (book == null) return NotFound();
            book.Title = updatedBook.Title;
            book.Author = updatedBook.Author;
            return NoContent();
        }

        [HttpDelete("{id}")]
        public IActionResult DeleteBook(int id)
        {
            var book = books.Find(b => b.Id == id);
            if (book == null) return NotFound();
            books.Remove(book);
            return NoContent();
        }
    }

    public class Book
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string Author { get; set; }
    }
}
    

What is GraphQL?

GraphQL is a query language for APIs that allows clients to request exactly the data they need. Unlike REST, where the server defines the structure of the returned data, in GraphQL, the client has control over the query, which can result in less data being transferred and fewer API calls. This flexibility is especially useful in mobile applications, where bandwidth may be limited (NISWAR et al., 2024).

The main feature of GraphQL is its ability to compose complex queries in a single call, allowing the client to fetch multiple resources in a single request. Additionally, GraphQL offers a strongly typed schema, which enhances documentation and validation of APIs.

Implementing a GraphQL API in .NET

To demonstrate the implementation of a GraphQL API in .NET, we will use the same book management system. Below, we present an example of configuration and a basic schema.


using GraphQL;
using GraphQL.Types;

public class Book
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Author { get; set; }
}

public class BookType : ObjectGraphType<Book>
{
    public BookType()
    {
        Field(b => b.Id);
        Field(b => b.Title);
        Field(b => b.Author);
    }
}

public class Query : ObjectGraphType
{
    public Query()
    {
        Field<BookType>("book",
            arguments: new QueryArguments(new QueryArgument<IntGraphType> { Name = "id" }),
            resolve: context => books.FirstOrDefault(b => b.Id == context.GetArgument<int>("id")));
        
        Field<ListGraphType<BookType>>("books",
            resolve: context => books);
    }
}

public class BookSchema : Schema
{
    public BookSchema(IDependencyResolver resolver) : base(resolver)
    {
        Query = resolver.Resolve<Query>();
    }
}
    

Comparison between REST and GraphQL

Both approaches have their advantages and disadvantages. REST is simpler to implement and understand, especially for developers familiar with the HTTP protocol. Additionally, the endpoint structure of REST is intuitive and easy to map. However, GraphQL can offer greater flexibility in queries and efficiency in API calls, especially in scenarios where multiple entities need to be retrieved simultaneously.

One of the strengths of GraphQL is its ability to avoid the problems of over-fetching and under-fetching, common in REST APIs. With GraphQL, clients can specify exactly which fields they need, avoiding unnecessary data transfers. On the other hand, the complexity of GraphQL queries can lead to performance challenges if not managed properly.

Challenges and Considerations

Although REST and GraphQL are powerful tools for API modeling, they also present challenges. With REST, managing multiple endpoints can become complex, especially in larger applications where the number of resources and operations grows. Additionally, implementing authentication and access control across multiple endpoints can be more labor-intensive.

On the other hand, GraphQL can introduce performance complications if not implemented well, such as excessive or complex queries that can overload the server. It is crucial to implement optimization techniques, such as limiting query depth and using caching tools, to mitigate these issues. Another challenge is ensuring that API documentation is always up to date, as queries may change frequently.

Best Practices in API Modeling

Regardless of the chosen approach, some best practices should be followed in API modeling:

  • Clear and accessible documentation, using tools like Swagger for REST or GraphiQL for GraphQL.
  • API versioning to ensure compatibility with older clients.
  • Consistent and informative error handling, using appropriate HTTP status codes and error messages that help in troubleshooting.
  • Proper authentication and authorization to protect data, using standards like OAuth to ensure API security.
  • Implementation of automated tests to ensure the API functions as expected and to avoid regressions during development.
  • Monitoring and performance analysis to identify bottlenecks and optimize the user experience.

Conclusion

API modeling is a fundamental part of modern software development. With the growing demand for integrations and services, it is crucial to choose the right approach for creating APIs. Both REST and GraphQL have roles to play, and the choice depends on the specific needs of each project. Using .NET to implement these APIs provides a robust set of tools and libraries to optimize development.

References

  • LOPEZOSA SERRANO, Ignacio et al. Analysis and comparison of API technologies: REST, GraphQL, and gRPC. 2024. reference.Description
  • SLIWA, Mariusz; PANCZYK, Beata. Performance comparison of programming interfaces on the example of REST API, GraphQL, and gRPC. Journal of Computer Sciences Institute, v. 21, p. 356-361, 2021. reference.Description
  • NISWAR, Muhammad et al. Performance evaluation of microservices communication with REST, GraphQL, and gRPC. International Journal of Electronics and Telecommunication, vol. 70, no. 2, pp. 429-436, 2024. reference.Description
About the author