Building REST-style web APIs

The REST style was invented by Roy Fielding in the 2000s and is one of the best ways to provide interoperability between systems that are based on multiple technologies, whether it be in your network or on the internet.

Furthermore, the REST approach is not a technology by itself, but some best practices that are used for efficiently using the HTTP protocol.

Instead of adding a new layer, like SOAP or XML-RPC does, REST uses different elements of the HTTP protocol for providing its services:

  • The URI identifies a resource.
  • The HTTP verb identifies an action.
  • The response is not the resource, but a representation of the resource.
  • The client authentication is passed as a parameter in the header of requests.

Unlike the RPC style, the main purpose is no longer to provide actions and is to manage and manipulate resources.

To find out even more about the concepts and ideas behind REST, you should read Roy Fielding's dissertation on this subject, which you can find at http://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm.

As shown in the following diagram, there are mainly three types of resources in the Tic-Tac-Toe application:

  • Users
  • Game invitations
  • Game sessions:

Let's learn how to use the REST style for building a game invitation with the REST API:

  1. Add two new methods, one called All, which returns all game invitations, and another called Delete, which deletes a game invitation according to the specified game invitation ID. You need to add these two methods to GameInvitationService and update the game invitation service interface accordingly:
        public Task<IEnumerable<GameInvitationModel>> All() 
        { 
          return Task.FromResult<IEnumerable<GameInvitationModel>>
(_gameInvitations.ToList()); } public Task Delete(Guid id) { _gameInvitations = new ConcurrentBag<GameInvitationModel>
(_gameInvitations.Where(x => x.Id != id)); return Task.CompletedTask; }
  1. Add a new API controller called GameInvitationApiController, right-click on the Controllers folder, and select Add | Controller. Then, choose the API Controller with read/write actions template:

  1. Remove the auto-generated code and replace it with the following REST API implementation:
    1. First, insert the following code as a scaffold for the game invitation API controller, where we have the decorators of expected output and the actual endpoint route. Then, we have a constructor that injects the game invitations service and the user service into the controller, as follows: 
        [Produces("application/json")] 
        [Route("restapi/v1/GameInvitation")] 
        public class GameInvitationApiController : Controller 
        { 
          private IGameInvitationService 
_gameInvitationService; private IUserService _userService; public GameInvitationApiController
(IGameInvitationService
gameInvitationService, IUserService userService) { _gameInvitationService = gameInvitationService; _userService = userService; }
... }
    1. Add the following two Get implementation methods. The first returns all the game invitation services, while the other returns a game invitation service according to the ID being specified as Guid
          [HttpGet] 
          public async Task<IEnumerable<GameInvitationModel>> Get() 
          { 
            return await _gameInvitationService.All(); 
          } 
 
          [HttpGet("{id}", Name = "Get")] 
          public async Task<GameInvitationModel> Get(Guid id) 
          { 
            return await _gameInvitationService.Get(id); 
          }
    1. Add a method that will be used for the creation or insertion of a game invitation, as follows: 
        [HttpPost] 
          public IActionResult Post([FromBody]GameInvitationModel 
invitation) { if (!ModelState.IsValid) return BadRequest(ModelState); var invitedPlayer =
_userService.GetUserByEmail(invitation.EmailTo); if (invitedPlayer == null) return BadRequest(); _gameInvitationService.Add(invitation); return Ok(); }
      1. Add the following method, which will be used for updating a game invitation: 
    [HttpPut("{id}")] 
              public IActionResult Put(Guid id,
    [FromBody]GameInvitationModel invitation) { if (!ModelState.IsValid) return BadRequest(ModelState); var invitedPlayer =
    _userService.GetUserByEmail(invitation.EmailTo); if (invitedPlayer == null) return BadRequest(); _gameInvitationService.Update(invitation); return Ok(); }
      1. Finally, we need to add our delete functionality so that we can delete a game invitation service according to the ID specified as being Guid
      [HttpDelete("{id}")] 
              public void Delete(Guid id) 
              { 
                _gameInvitationService.Delete(id); 
              }
    Note that, for learning purposes, we have just provided a very basic example of what you could implement. Normally, you should provide the same functionalities as in your controller implementations (sending emails, confirming emails, verifying data, and so on) and some advanced error handling.
    1. Start the application, install and start Postman so that you can do some manual tests on the new REST API you are providing, and send an HTTP GET request to http://<yourhost>/restapi/v1/GameInvitation. There will be no game invitations since you haven't created any yet:

    1. Create a new game invitation, send an HTTP POST request to http://<yourhost>/restapi/v1/GameInvitation, click on Body, select raw and JSON, and use "id":"7223160d-6243-498b-9d35-81b8c947b5ca", "EmailTo":"[email protected]", and "InvitedBy":"[email protected]" as parameters:

    Note that we have added the automatic creation of a user if one doesn't exist for testing purposes in Chapter 4Basic Concepts of ASP.NET Core 3 via a Custom Application: Part 1. In a real-world scenario, you will have to implement the user registration web APIs and call them before the game invitation web APIs. If you don't, you'll get a bad request since we have added some code to ensure data coherence and integrity.
    1. You can retrieve the game invitation either by sending an HTTP GET request to http://<yourhost>/restapi/v1/GameInvitation or, more specifically, by sending an HTTP GET request to http://<yourhost>/restapi/v1/GameInvitation/7223160d-6243-498b-9d35-81b8c947b5ca:

    1. Update the game invitation, send an HTTP PUT request to http://<yourhost>/restapi/v1/GameInvitation/7223160d-6243-498b-9d35-81b8c947b5ca, click on Body, select raw and JSON, and use "id":"7223160d-6243-498b-9d35-81b8c947b5ca", "EmailTo":"[email protected]", and "InvitedBy":"[email protected]" as parameters:

    1. Look at the updated game invitation and send an HTTP GET request to http://<yourhost>/restapi/v1/GameInvitation/7223160d-6243-498b-9d35-81b8c947b5ca:

    1. Delete the game invitation and send an HTTP DELETE request to http://<yourhost>/restapi/v1/GameInvitation/7223160d-6243-498b-9d35-81b8c947b5ca:

    1. Verify the game invitation's deletion and send an HTTP GET request to http://<yourhost>/restapi/v1/GameInvitation:

    The REST style is the most common style of web APIs you can find on the market today. It is easy to understand and has been adapted for interoperability use cases.

    In the next section, you will learn about a more advanced style called HATEOAS, which is especially well suited for constantly evolving web APIs.

    ..................Content has been hidden....................

    You can't read the all page of ebook, please click here login for view all page.
    Reset
    3.136.236.231