Skip to content

.NET Core Microservices - The Complete Guide [2026] - 3. Modifications to Existing API

Tutor: Bhrugen Patel

Course Link

Section length: 5 lectures

← Previous: 2. Solution Setup | Course overview | Next: 4. Consuming Coupon API →

Summary

This section completes the implementation of the Coupon API.

Key Takeaways

Lecture Notes

Generic Response DTO

The API as currently returning the database entity model. Microservices should aim to return a unified model to keep things more simple. We need a standard generic response across the microservices. This should therefore be defined in a shared class library where all microservices can access this definition.

Add a new Class Library to the Services folder named Mango.Services.Shared.

Delete Class1.cs and create a new folder Models. In the Models folder add the new class ResponseDto as:

namespace Mango.Services.Shared.Models;

public class ResponseDTO
{
    public object? Result { get; set; }
    public bool IsSuccess { get; set; } = true;
    public string? ErrorMessage { get; set; }
}

Note: Jumping ahead a little here, I would have probably used generics for this, but we'll see later in the course, he may have a good reason of why not to.

Return Response DTO and Update GetAllCoupon

With the generic ResponseDTO defined, we can start standardising our API.

First add the class library to the project references list.

Then update CouponAPIController to hold the ResponseDto and injectable IMapper instance:

public class CouponAPIController : ControllerBase
{
    private readonly ApplicationDbContext _context;
    private readonly IMapper _mapper;
    private ResponseDTO _response;

    public CouponAPIController(ApplicationDbContext context, IMapper mapper)
    {
        _context = context;
        _mapper = mapper;
        _response = new ResponseDTO();
    }

    ...
}

The standard response approach we will use in all the endpoints will be based on this:

try
{
    // Individual endpoint logic goes here
}
catch (Exception ex)
{
    _response.IsSuccess = false;
    _response.ErrorMessage = ex.Message;

    return BadRequest(_response);
}
return Ok(_response);

Now we have everything in place we can modify the GET verb endpoint (and also change its name from GetCoupon to GetAllCoupons):

// GET: api/Coupon
[HttpGet]
public async Task<ActionResult<ResponseDTO>> GetAllCoupons()
{
    try
    {
        IEnumerable<Coupon> couponList = await _context.Coupons.ToListAsync();
        _response.Result = _mapper.Map<IEnumerable<Coupon>>(couponList);
    }
    catch (Exception ex)
    {
        _response.IsSuccess = false;
        _response.ErrorMessage = ex.Message;

        return BadRequest(_response);
    }
    return Ok(_response);
}

This can be tested via the Scalar UI.

Fix all Endpoints

The other endpoints can now be modified to follow this pattern:

// GET: api/Coupon/5
[HttpGet("{id:int}")]
public async Task<ActionResult<ResponseDTO>> GetCouponById(int id)
{
    try
    {
        var coupon = await _db.Coupons.FindAsync(id);

        if (coupon != null)
        {
            _response.Result = _mapper.Map<Coupon>(coupon);
        }
        else
        {
            _response.IsSuccess = false;
            _response.ErrorMessage = "Coupon not found.";
            return NotFound(_response);
        }
    }
    catch (Exception ex)
    {
        _response.IsSuccess = false;
        _response.ErrorMessage = ex.Message;

        return BadRequest(_response);
    }
    return Ok(_response);
}

// PUT: api/Coupon/5
// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
[HttpPut]
public async Task<IActionResult> UpdateCoupon([FromBody] CouponDto couponDto)
{
    try
    {
        if (!CouponExists(couponDto.CouponId))
        {
            _response.IsSuccess = false;
            _response.ErrorMessage = "Coupon not found for update.";
            return NotFound(_response);
        }
        if (couponDto == null || couponDto.CouponId <= 0)
        {
            _response.IsSuccess = false;
            _response.ErrorMessage = "Coupon Id is required for update.";
            return BadRequest(_response);
        }

        var coupon = _mapper.Map<Coupon>(couponDto);
        _db.Coupons.Update(coupon);
        await _db.SaveChangesAsync();
        _response.Result = _mapper.Map<Coupon>(coupon);
    }
    catch (Exception ex)
    {
        _response.IsSuccess = false;
        _response.ErrorMessage = ex.Message;

        return BadRequest(_response);
    }
    return Ok(_response);
}

// POST: api/Coupon
// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
[HttpPost]
public async Task<ActionResult<ResponseDTO>> CreateCoupon([FromBody] CreateCouponDto couponDto)
{
    try
    {
        var coupon = couponDto.Adapt<Coupon>();
        // _mapper.Map<Coupon>(couponDto);
        _db.Coupons.Add(coupon);
        await _db.SaveChangesAsync();
        _response.Result = _mapper.Map<Coupon>(coupon);
    }
    catch (Exception ex)
    {
        _response.IsSuccess = false;
        _response.ErrorMessage = ex.Message;

        return BadRequest(_response);
    }
    return Ok(_response);
}

// DELETE: api/Coupon/5
[HttpDelete("{id:int}")]
public async Task<IActionResult> DeleteCoupon(int id)
{
    try
    {

        var coupon = await _db.Coupons.FindAsync(id);
        if (coupon == null)
        {
            _response.IsSuccess = false;
            _response.ErrorMessage = "Coupon not found for deletion.";
            return NotFound(_response);
        }

        _db.Coupons.Remove(coupon);
        await _db.SaveChangesAsync();
    }
    catch (Exception ex)
    {
        _response.IsSuccess = false;
        _response.ErrorMessage = ex.Message;

        return BadRequest(_response);
    }
    return Ok(_response);
}

I also added another DTO for Coupon creation as we shouldn't supply an Id, although the course doesn't do this, but I feel this is fundamentally bad:

namespace Mango.CouponAPI.DTOs;

public class CreateCouponDto
{
    public string CouponCode { get; set; } = string.Empty;
    public double DiscountAmount { get; set; }
    public int MinAmount { get; set; }
}

Once this is all in place you can test the endpoints.


← Previous: 2. Solution Setup | Course overview | Next: 4. Consuming Coupon API →