In this guide, we will walk through the process of creating a basic RESTful API using ASP.NET Core.
ASP.NET Core is a powerful and versatile framework for building web applications and APIs. By the end of this guide, you will have a simple API that can perform CRUD (Create, Read, Update, Delete) operations on a resource.
Pre-requisites
Before we get started, make sure you have the following installed:
Visual Studio or Visual Studio Code.
.NET SDK.
Step 1: Create a New ASP.NET Core Project.
• Open Visual Studio or Visual Studio Code.
• Create a new ASP.NET Core project using the "Web API"
template.
Step 2: Define Your Model.
In this example, let's create a simple API for managing a
list of books. Define a Book model in a C# class:
{
public int Id { get; set; }
public string Title { get; set; }
public string Author { get; set; }
}
Step 3: Create a Controller
Create a controller that will handle HTTP requests for
managing books. In ASP.NET Core, controllers are
responsible for processing incoming requests and returning
responses. Here's a basic example of a controller:
[Route("api/books")]
[ApiController]
public class BooksController : ControllerBase
{
private readonly List<Book> _books = new List<Book>
{
new Book { Id = 1, Title = "Book 1", Author = "Author 1" },
new Book { Id = 2, Title = "Book 2", Author = "Author 2" }
};
// Implement your CRUD operations here.
}
Step 4: Implement CRUD Operations.
Within the BooksController, implement CRUD operations such
as GET, POST, PUT, and DELETE to interact with the Book
model. Here are some examples:
// GET: api/books
[HttpGet]
public ActionResult<IEnumerable<Book>> Get()
{
return _books;
}
// GET: api/books/{id}
[HttpGet("{id}")]
public ActionResult<Book> Get(int id)
{
var book = _books.FirstOrDefault(b => b.Id == id);
if (book == null)
{
return NotFound();
}
return book;
}
// POST: api/books
[HttpPost]
public ActionResult<Book> Post([FromBody] Book book)
{
book.Id = _books.Count + 1;
_books.Add(book);
return CreatedAtAction(nameof(Get), new { id = book.Id }, book);
}
// PUT: api/books/{id}
[HttpPut("{id}")]
public ActionResult Put(int id, [FromBody] Book book)
{
var existingBook = _books.FirstOrDefault(b => b.Id == id);
if (existingBook == null)
{
return NotFound();
}
existingBook.Title = book.Title;
existingBook.Author = book.Author;
return NoContent();
}
// DELETE: api/books/{id}
[HttpDelete("{id}")]
public ActionResult Delete(int id)
{
var book = _books.FirstOrDefault(b => b.Id == id);
if (book == null)
{
return NotFound();
}
_books.Remove(book);
return NoContent();
}
Step 5: Run the API
Build and run your ASP.NET Core API project. You can use
tools like Postman or Curl to test your API endpoints.
Note
This guild assumes you already know the process of creating a new project from the visual studio or visual studio code using a web API template.
Top comments (0)