Content

  • Swagger UI
  • Status Codes
  • Exception Handling in Web API
  • Async Programming in Web API
  • Content Negotiation

Swagger UI

  • Swagger UI is used for testing, documenting, and visualizing RESTful APIs in an intuitive and user-friendly interface. It simplifies the development process, increases efficiency, and enhances user experience when consuming APIs.
  • Swagger UI is included and configured by default when you create an ASP.NET Core Web API project in Visual Studio 2022. It provides an interactive web-based interface for exploring and testing your API

Status Codes

HTTP Status Codes are standard response codes sent by the server to inform the client about the result of an API request. They help developers understand whether a request was successful or failed.

HTTP Status Codes

Status Code Range Category Short Description
1xx Informational Request received and processing is continuing.
2xx Success Request successfully received, understood, and processed.
3xx Redirection Client must take additional action to complete the request.
4xx Client Error Request contains invalid data or is not allowed.
5xx Server Error Server failed to process a valid request.

Exception Handling in Web API

Exception handling in Web API is the process of capturing runtime errors and returning meaningful, consistent HTTP responses to the client instead of application crashes or unhandled errors.

Example : Status Codes and Exception handling

using API_Sessions.Data;
using API_Sessions.Models;
using Microsoft.AspNetCore.Mvc;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace API_Sessions.Controllers
{
    
    [Route("api/[controller]")]
    [ApiController]
    public class ProductDBController : ControllerBase
    {
        private readonly ApplicationDbContext _context;

        public ProductDBController(ApplicationDbContext context)
        {
            _context = context;
        }

        // GET: api/<ProductDBController>
        [HttpGet]
        public IActionResult Get()
        {
            return Ok(_context.Products.ToList());
        }

        // GET api/<ProductDBController>/5
        [HttpGet("{id}")]
        public IActionResult Get(int id)
        {
            var product = _context.Products.Find(id);
            if(product == null)
            {
                return NotFound();
            }
            return Ok(product);
        }

        // POST api/<ProductDBController>
        [HttpPost]
        public IActionResult Post([FromBody] Product product)
        {
            _context.Products.Add(product);
            _context.SaveChanges();
            return StatusCode(StatusCodes.Status201Created);
        }

        // PUT api/<ProductDBController>/5
        [HttpPut("{id}")]
        public IActionResult Put(int id, [FromBody] Product product)
        {
            //exception handling
            var p = _context.Products.FirstOrDefault(x=>x.Id==id);
            if (p == null) {
            return NotFound();
            }
            else
            {
                p.Name = product.Name;
                p.Price = product.Price;
                _context.SaveChanges();
                return Ok("Product details updated");
            }
           

        }

        // DELETE api/<ProductDBController>/5
        [HttpDelete("{id}")]
        public IActionResult Delete(int id)
        {
            var p = _context.Products.Find(id);
            _context.Products.Remove(p);
            _context.SaveChanges();
            return Ok("Product deleted");

        }
    }
}

Async Programming in Web API

  • Async programming allows a Web API to handle multiple requests efficiently without blocking threads while waiting for long-running operations such as database calls, file access, or external API requests.
  • In ASP.NET Web API, async programming is implemented using the async and await keywords. Instead of waiting synchronously, the thread is released and reused to process other requests, improving performance and scalability.

Example: async programming

using API_Sessions.Data;
using API_Sessions.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace API_Sessions.Controllers
{
    
    [Route("api/[controller]")]
    [ApiController]
    public class ProductDBController : ControllerBase
    {
        private readonly ApplicationDbContext _context;

        public ProductDBController(ApplicationDbContext context)
        {
            _context = context;
        }

        // GET: api/<ProductDBController>
        [HttpGet]
        public async Task<IActionResult> Get()
        {
            return Ok(await _context.Products.ToListAsync());
        }

        // GET api/<ProductDBController>/5
        [HttpGet("{id}")]
        public async Task<IActionResult> Get(int id)
        {
            var product = await _context.Products.FirstOrDefaultAsync(x=>x.Id==id);
            if(product == null)
            {
                return NotFound();
            }
            return Ok(product);
        }

        // POST api/<ProductDBController>
        [HttpPost]
        public async Task<IActionResult> Post([FromBody] Product product)
        {
            await _context.Products.AddAsync(product);
            await _context.SaveChangesAsync();
            return StatusCode(StatusCodes.Status201Created);
        }

        // PUT api/<ProductDBController>/5
        [HttpPut("{id}")]
        public async Task<IActionResult> Put(int id, [FromBody] Product product)
        {
            //exception handling
            var p = await _context.Products.FirstOrDefaultAsync(x=>x.Id==id);
            if (p == null) {
            return NotFound();
            }
            else
            {
                p.Name = product.Name;
                p.Price = product.Price;
                await _context.SaveChangesAsync();
                return Ok("Product details updated");
            }
           

        }

        // DELETE api/<ProductDBController>/5
        [HttpDelete("{id}")]
        public async Task<IActionResult> Delete(int id)
        {
            var p = await _context.Products.FindAsync(id);
            _context.Products.Remove(p);
            await _context.SaveChangesAsync();
            return Ok("Product deleted");

        }
    }
}

Content Negotiation

  • Content Negotiation is the process by which a Web API selects the best response format (such as JSON or XML) based on the client’s request.
  • When a client sends a request, it includes an Accept header specifying the preferred response format. The server examines this header and returns the response in the most appropriate format it supports.

Code: update in program.cs to support Content Negotiation

builder.Services.AddMvc().AddXmlSerializerFormatters();