Search code examples
c#asp.netasp.net-web-apicontroller

How to implement routing similar to Trello's API


I would like to implement such API which would allow me to get Tour entities using api/tours and api/bands/{bandId}/tours. It seems like I can't get me head around it. Should I have two separate controllers for boths endpoints? Do I need two repositories as well?

This is how I've implemented api/bands/{bandId}/tours endpoint.

using BandManager.Domain;
using Microsoft.AspNetCore.JsonPatch;
using Microsoft.AspNetCore.Mvc;

namespace BandManager.Api.Controllers
{
    [Route("api/bands/{bandId}/tours")]
    [ApiController]
    public class ToursController : ControllerBase
    {
        private readonly IBandInfoRepository _repo;
        private readonly IMapper _mapper;

        public ToursController(IBandInfoRepository repository, IMapper mapper)
        {
            _repo = repository ?? throw new ArgumentNullException(nameof(repository));
            _mapper = mapper ?? throw new ArgumentNullException(nameof(mapper));
        }

        [HttpGet]
        public async Task<ActionResult<IEnumerable<TourDto>>> Get(int bandId)
        {
            var band = await _repo.GetBandAsync(bandId);
            return band is null
                ? NotFound()
                : Ok(_mapper.Map<IEnumerable<TourDto>>(band.Tours));
        }
    }
}

Trello's API have this feature implemented for Card resource. Get a Card on a Board / Get a Card


Solution

  • Why do you want to create another controller and repository while both endpoint will give you tour's data. You can do it using single controller and repository.

    What you need is two different method to get data from api/tours and api/bands/{bandId}/tours endpoint.

    Also you shouldn’t use RouteAttribute on top of controller. Rather you should use Route attribute on top of ActionMethod. This way you can do it in single controller and repository and that should be the way.