How i will return status code & message depend on condition in API?

        [HttpGet("{id:int}")]
        public ActionResult <VillaDTO> GetVilla(int id)
        {

            if (id == 0) {
                return BadRequest(); //return 400
            }

            var villa = VillaStore.villasList.FirstOrDefault(u => u.Id == id);

            if (villa == null) {
                return NotFound(); //return 404 not found
            }

            return Ok(villa); //return 200 success
        }

Here when user try to get data entering id. If user enter id zero(0) then it’s called BadRequest which return 400. If user enter any id which is not exist in list then user will get 404 code which means data not found. If data exist then user will get 200 code with success message.

9 thoughts on “How i will return status code & message depend on condition in API?

Leave a Reply

Your email address will not be published. Required fields are marked *