Outline

Demo - API Routes with Variables

According to the Conduit Route Specification, we need to provide some parameters to ensure we’re targeting the correct data when making a request.

  • DELETE /api/articles/:slug
  • POST /api/article/:slug/comments
  • GET /api/articles/:slug/comment
  • DELETE /api/articles/:slug/comment/:id
  • POST /api/articles/:slug/favorite

Using a colon along with a variable name is a common standard when designing api routes.

using Conduit.Models.Requests;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;

namespace Conduit.Api.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ArticlesController : ControllerBase…
}

If you recall, asp.net provides a base url where the controller enclosed with square brackets is automatically replace with the controller name.

[HttpDelete("{slug}")]
[Authorize]
public IActionResult DeleteArticle([FromQuery]string slug)…

[HttpPost("{slug}/comments")]
[Authorize]
public IActionResult AddCommentsToArticle([FromBody]CommentRequest<CommentAddRequest> req)…

[HttpGet("{slug}/comments")]
public IActionResult GetCommentsFromArticle([FromQuery]string slug)…

[HttpDelete("{slug}/comments/{id:int}")]
[Authorize]
public IActionResult DeleteCommentFromArticle(
     [FromQuery]string slug,
     [FromQuery]int id)…

Knowing that, we don’t have to worry about the base we simply provide the route for the what’s left in the url.

The variables are replaced with tokens enclosed in curly braces that default to a type string.

While variables that are a different type need to be specified in the route configuration. Let's create a few of these methods in the api controller so that we can get a better feel for how this code should look.

 

I finished! On to the next chapter