Hello everyone! Here we are continue to build our .NET 5 Web API. If you have missed the first part, please visit the introduction here.
In the previous article, we have implemented the method to get all the movies. So here we can start with the method, Get movie by id to get a single movie from database. We can just simply add the below method to get a movie by id.
[HttpGet("{id}")]
public async Task<ActionResult<Movie>> GetMovie(int id)
{
var movie = await _context.Movie.FindAsync(id); if (movie == null)
{
return NotFound();
}
return movie;
}
Once we run the project, swagger will nicely generate the specification for us like following. It shows us the id parameter is required and how the schema looks like. So the client can get an idea about the JSON object which we are returning.
Add all controller methods
Same as we can add the Post method to create a movie, Put method to update and Delete method to delete a movie.
// PUT: api/Movies/5
[HttpPut("{id}")]
public async Task<IActionResult> PutMovie(int id, Movie movie)
{
if (id != movie.Id)
{
return BadRequest();
}
_context.Entry(movie).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!MovieExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
// POST: api/Movies
[HttpPost]
public async Task<ActionResult<Movie>> PostMovie(Movie movie)
{
_context.Movie.Add(movie);
await _context.SaveChangesAsync(); return CreatedAtAction("GetMovie", new { id = movie.Id }, movie);
}
// DELETE: api/Movies/5
[HttpDelete("{id}")]
public async Task<ActionResult<Movie>> DeleteMovie(int id)
{
var movie = await _context.Movie.FindAsync(id);
if (movie == null)
{
return NotFound();
}
_context.Movie.Remove(movie);
await _context.SaveChangesAsync(); return movie;
}
private bool MovieExists(int id)
{
return _context.Movie.Any(e => e.Id == id);
}
Now we can run our basic .NET 5 Web API and see the all basic methods in swagger.
Its always better to do the testing before we go far more. So we can see now we can Get all the movies from our web API and also get one by one, create new movies, update and also delete a particular movie by id. So far we have covered the basic CRUD operations with our new .NET 5 Web API. To test this we can use Postman as a client tool. We can copy the JSON objects from swagger and paste in Postman and change the values.
Is this all we can do? oh wait something is still wrong! Our Web API is not secured yet. So anyone can access it and use it. In that case definitely we have to secure our web API. Lets discuss how to secure and authenticate our API in the next article.
2 thoughts on “.NET 5 Web API – Part 2”