Introduction:
Welcome to this beginner-friendly guide where we’ll delve into building a straightforward API for book management using the T Web API framework. By following along, you’ll grasp the fundamentals of API development and gain hands-on experience in crafting your own API from the ground up.
Setting Up Our Project:
To get started, open up your preferred code editor, whether it’s Visual Studio or another tool, and initiate a new.NET Web API project. Let’s give it the name “BookManagementAPI” for the sake of this tutorial. Once the project is initialized, we’re all set to dive into the coding process.
Defining Our Data Model:
Every API needs to handle data, and ours is no different. Let’s define the data model for our books. In our scenario, a book consists of attributes like title, author, and publication year. We’ll create a C# class to represent this entity:
using System.ComponentModel.DataAnnotations;
public class Book
{
public int Id { get; set; }
[Required]
public string Title { get; set; }
[Required]
public string Author { get; set; }
public int Year { get; set; }
}
Creating Our Database Context: Now that we have our data model. we need a way to interact with the database. Entity Framework Core makes this task straightforward. We’ll create a DbContext class that represents our database context:
using Microsoft.EntityFrameworkCore;
public class BookDbContext : DbContext
{
public DbSet<Book> Books { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("YourConnectionReReReplace it it ");
}
}
Replace "YourConnectionStringHere"
with your actual database connection string.
Writing Our Controller: With our data model and database context in place, it’s time to create the controller that will handle incoming requests to our API. We’ll define endpoints for actions like adding a new book, getting a list of all books, updating a book, and deleting a book:
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
[Route("api/books")]
[ApiController]
public class BooksController : ControllerBase
{
private readonly BookDbContext _context;
public BooksController(BookDbContext context)
{
_context = context;
}
[HttpGet]
public ActionResult<IEnumerable<Book>> GetBooks()
{
return _context.Books.ToList();
}
[HttpGet("{id}")]
public ActionResult<Book> GetBook(int id)
{
var book = _context.Books.Find(id);
if (book == null)
{
return NotFound();
}
return book;
}
[HttpPost]
public IActionResult CreateBook(Book book)
{
_context.Books.Add(book);
_context.SaveChanges();
return CreatedAtAction(nameof(GetBook), new { id = book.Id }, book);
}
[HttpPut("{id}")]
public IActionResult UpdateBook(int id, Book book)
{
if (id != book.Id)
{
return BadRequest();
}
_context.Entry(book).State = EntityState.Modified;
_context.SaveChanges();
return NoContent();
}
[HttpDelete("{id}")]
public IActionResult DeleteBook(int id)
{
var book = _context.Books.Find(id);
if (book == null)
{
return NotFound();
}
_context.Books.Remove(book);
_context.SaveChanges();
return NoContent();
}
}
Testing Our API: With our API code written, it’s time to test it out. Fire up your favorite API testing tool, such as Postman, and send some requests to our API endpoints. Try adding a new book, retrieving a list of books, updating a book, and deleting a book to see how our API responds.
Conclusion:
In summary, we’ve crafted a basic Book Management API with .NET Web API, covering essential steps from defining data models to testing endpoints. This beginner-friendly tutorial sets the stage for deeper dives into API development, encouraging ongoing learning and exploration.
For more info : https://learn.microsoft.com/en-us/ef/ef6/modeling/code-first/workflows/new-database
More blgs:https://athen.tech/a-deep-dive-into-cors-in-net-core-web-api/
No Comment! Be the first one.