Création d'une API REST avec le Routing d'Attributs dans Web API 2 (2024)

Introduction

Dans le monde du développement web, la création d'API RESTful est devenue une pratique courante. Dans cet article, nous explorerons en profondeur le routing d'attributs dans Web API 2, en mettant l'accent sur la création d'une API REST pour une collection de livres.

Configuration du Projet

Commencez par créer un nouveau projet dans Visual Studio 2017, en choisissant le modèle d'application Web API (.NET Framework). Nommez le projet "BooksAPI" et assurez-vous de sélectionner le modèle vide avec la prise en charge de Web API.

Modèles de Domaine

Ajoutez les classes de modèles de domaine pour représenter les auteurs et les livres. Utilisez Entity Framework comme couche de données. La classe Author représente un auteur, tandis que la classe Book représente un livre avec des détails tels que le titre, le genre, la date de publication, etc.

Contrôleur Web API

Ajoutez un contrôleur Web API qui utilise Entity Framework comme couche de données. Ce contrôleur, nommé "BooksController," permet d'effectuer des opérations de lecture sur la collection de livres. Les actions du contrôleur retournent des instances de Data Transfer Objects (DTO) pour une meilleure gestion des données.

Seed de la Base de Données

Utilisez la console du Gestionnaire de package NuGet pour créer une migration et mettre à jour la base de données avec des données de test. Cette étape assure que la base de données est préremplie avec des auteurs et des livres.

DTO Classes

Ajoutez des classes DTO pour spécifier les données que l'API renverra. Les classes BookDto et BookDetailDto définissent les structures de données pour les livres avec des détails réduits et complets respectivement.

Mise à Jour du Contrôleur pour Utiliser les DTO

Modifiez le code du contrôleur pour retourner des instances de DTO au lieu des modèles EF. Utilisez la méthode Queryable.Select pour projeter les instances de Book en instances de DTO. Les méthodes du contrôleur telles que GetBooks et GetBookDetail doivent être mises à jour en conséquence.

Ajout de Routage par Attributs

Pour rendre le contrôleur plus flexible et lisible, utilisez le routage par attributs. Ajoutez l'attribut [RoutePrefix("api/books")] pour définir le préfixe commun pour toutes les actions du contrôleur. Ensuite, ajoutez des attributs [Route] aux méthodes du contrôleur pour spécifier les URI correspondantes.

Exemples d'URI

  • Récupérer la liste des livres :

    • URI : /api/books
    • Méthode : GET
  • Récupérer les détails d'un livre :

    • URI : /api/books/1/details
    • Méthode : GET
  • Récupérer la liste des livres par genre :

    • URI : /api/books/fantasy
    • Méthode : GET
  • Récupérer la liste des livres par auteur :

    • URI : /api/authors/1/books
    • Méthode : GET
  • Récupérer la liste des livres par date de publication :

    • URI : /api/books/date/2023-11-10
    • Méthode : GET

Conclusion

En conclusion, la mise en œuvre du routing d'attributs dans Web API 2 offre une flexibilité accrue pour la conception des URIs dans votre API REST. En suivant ces étapes, vous pouvez créer une API robuste pour gérer une collection de livres, tout en fournissant des fonctionnalités de recherche avancées par genre, auteur et date de publication. Utilisez cette approche pour optimiser votre API et offrir une expérience utilisateur exceptionnelle.

Création d'une API REST avec le Routing d'Attributs dans Web API 2 (2024)

FAQs

What is the use of attribute routing in Web API? ›

Attribute routing gives you more control over the URIs in your web API. For example, you can easily create URIs that describe hierarchies of resources. The earlier style of routing, called convention-based routing, is still fully supported. In fact, you can combine both techniques in the same project.

How does routing work in REST API? ›

A route can have multiple endpoints associated with it, and which is used depends on the HTTP verb. For example, with the URL `http://example.com/wp-json/wp/v2/posts/123`: The “route” is wp/v2/posts/123 – The route doesn't include wp-json because wp-json is the base path for the API itself.

Which types of routing is supported in Web API 2? ›

Web API 2 supports a new type of routing, called attribute routing. As the name implies, attribute routing uses attributes to define routes. Attribute routing gives you more control over the URIs in your web API.

What are the two ways to implement routing in Web API? ›

It routes an incoming HTTP request to a particular action method on a Web API controller. Web API supports two types of routing: Convention-based Routing. Attribute Routing.

What is the difference between attribute routing and conventional routing in Web API? ›

Conventional routing: The route is determined based on conventions that are defined in route templates that, at runtime, will map requests to controllers and actions (methods). Attribute-based routing: The route is determined based on attributes that you set on your controllers and methods.

How do I enable attribute routing? ›

Enabling attribute routing in your ASP.NET MVC5 application is simple, just add a call to routes. MapMvcAttributeRoutes() method within RegisterRoutes() method of RouteConfig. cs file. You can also combine attribute routing with convention-based routing.

What is the difference between API and route? ›

API is usually a definition term, Endpoint or route are physical representation. When somebody says "build an API" that means you have to define its specification e.g. protocol, request/response schema, (may be) security credentials and (of course) an endpoint to hit.

How to write API routes? ›

API Routes let you create an API endpoint inside a Next.js app. You can do so by creating a function inside the pages/api directory that has the following format: // req = HTTP incoming message, res = HTTP server response export default function handler(req, res) { // ... }

What is the difference between API and rest endpoint? ›

Understanding the differences between REST APIs and RESTified endpoints is crucial. REST APIs represent traditional methods of resource access, while RESTified endpoints offer a more dynamic and efficient approach, particularly in environments that necessitate rapid development and flexibility.

What are the 3 types of routing protocols? ›

In the Internet, there are three types of routing protocols commonly used. They are: distance vector, link state, and path vector. In this chapter, we present the basic concepts and fundamentals behind each of these three types of protocols in a generic framework.

How do I enable attribute routing in Web API? ›

In Web API 2, the Attribute Routing is enabled by default. The config. MapHttpAttributeRoutes(); code which is present in WebApiConfig. cs file enables the Web API Attribute Routing.

What are the types of routing in Web API? ›

Convention-Based Routing and Attribute Routing are the two types of Routing.

How routing is done in API gateway? ›

Routing API requests

When a client sends an API request, API Gateway first determines which stage to route the request to. If the request explicitly matches a stage, API Gateway sends the request to that stage. If no stage fully matches the request, API Gateway sends the request to the $default stage.

What are the two main types of routing? ›

Types of Routing

Routing can be classified into three categories: Static Routing. Default Routing. Dynamic Routing.

What is the purpose of API controller attribute? ›

The [ApiController] attribute applies inference rules for the default data sources of action parameters. These rules save you from having to identify binding sources manually by applying attributes to the action parameters.

What is attribute routing in Web API 6? ›

As the name implies, attribute routing means attributes are used to define routes. The Attribute routing provides more control over the URIs in your Web API application by defining routes directly on the actions and controllers. For example, you can easily create URIs that describes the hierarchies of resources.

Why do we need attribute routing in MVC? ›

Attribute Routing provides us with more control over the URIs of our MVC web application. Previous routing mode (convention-based routing) is fully supported by this version of MVC. We may also use the two types of routing within the same project.

Top Articles
Latest Posts
Article information

Author: Rev. Porsche Oberbrunner

Last Updated:

Views: 5411

Rating: 4.2 / 5 (53 voted)

Reviews: 92% of readers found this page helpful

Author information

Name: Rev. Porsche Oberbrunner

Birthday: 1994-06-25

Address: Suite 153 582 Lubowitz Walks, Port Alfredoborough, IN 72879-2838

Phone: +128413562823324

Job: IT Strategist

Hobby: Video gaming, Basketball, Web surfing, Book restoration, Jogging, Shooting, Fishing

Introduction: My name is Rev. Porsche Oberbrunner, I am a zany, graceful, talented, witty, determined, shiny, enchanting person who loves writing and wants to share my knowledge and understanding with you.