logologo
  • AI Tools

    DB Query GeneratorMock InterviewResume BuilderLearning Path GeneratorCheatsheet GeneratorAgentic Prompt GeneratorCompany ResearchCover Letter Generator
  • XpertoAI
  • MVP Ready
  • Resources

    CertificationsTopicsExpertsCollectionsArticlesQuestionsVideosJobs
logologo

Elevate Your Coding with our comprehensive articles and niche collections.

Useful Links

  • Contact Us
  • Privacy Policy
  • Terms & Conditions
  • Refund & Cancellation
  • About Us

Resources

  • Xperto-AI
  • Certifications
  • Python
  • GenAI
  • Machine Learning

Interviews

  • DSA
  • System Design
  • Design Patterns
  • Frontend System Design
  • ReactJS

Procodebase © 2024. All rights reserved.

Level Up Your Skills with Xperto-AI

A multi-AI agent platform that helps you level up your development skills and ace your interview preparation to secure your dream job.

Launch Xperto-AI

Building RESTful APIs with ASP.NET Core

author
Generated by
Parveen Sharma

19/09/2024

ASP.NET Core

Sign in to read full article

Building RESTful APIs is a fundamental task in modern web development. Given the rise of microservices and the need for scalable web applications, knowing how to create an effective API can significantly enhance your skillset as a developer. In this post, we will look at how to leverage ASP.NET Core, a powerful framework, to develop RESTful APIs.

What is a RESTful API?

Before we dive into the how-to, let's establish what a RESTful API is. Representational State Transfer (REST) is an architectural style that defines a set of constraints and properties based on HTTP. RESTful APIs use standard HTTP methods like GET, POST, PUT, and DELETE to interact with resources, which are typically represented in JSON or XML format.

Setting Up Your ASP.NET Core Project

To create a RESTful API using ASP.NET Core, you'll first need to set up your development environment. Here’s how:

  1. Install SDK: Ensure that you have the .NET SDK installed on your machine. You can download it from the official .NET website.

  2. Create a New Project: Use the command line to create a new ASP.NET Core Web API project:

    dotnet new webapi -n MyRestfulApi
    

    This command sets up a new project named "MyRestfulApi" with the necessary structure.

  3. Open the Project: Navigate into your project directory:

    cd MyRestfulApi
    
  4. Run the Application: You can start the application using:

    dotnet run
    

    By default, your API will be accessible at http://localhost:5000.

Creating a Sample API

Now, let’s create a simple RESTful API to manage a collection of books. We’ll simulate a simple database using an in-memory list.

Step 1: Define the Model

First, let's create a model class for our Book entity. Create a new folder named Models in your project, and then create a file called Book.cs.

// Models/Book.cs using System.ComponentModel.DataAnnotations; namespace MyRestfulApi.Models { public class Book { public int Id { get; set; } [Required] public string Title { get; set; } [Required] public string Author { get; set; } } }

Step 2: Create a Data Storage

Next, we'll simulate a simple database with an in-memory list. We can create a new folder called Data and inside it, add a class named BookStore.

// Data/BookStore.cs using MyRestfulApi.Models; using System.Collections.Generic; using System.Linq; namespace MyRestfulApi.Data { public class BookStore { private static List<Book> books = new List<Book> { new Book { Id = 1, Title = "1984", Author = "George Orwell" }, new Book { Id = 2, Title = "The Catcher in the Rye", Author = "J.D. Salinger" } }; public List<Book> GetAllBooks() => books; public Book GetBookById(int id) => books.FirstOrDefault(b => b.Id == id); public void AddBook(Book book) { book.Id = books.Count + 1; books.Add(book); } public void UpdateBook(Book book) { var index = books.FindIndex(b => b.Id == book.Id); if (index != -1) { books[index] = book; } } public void DeleteBook(int id) => books.RemoveAll(b => b.Id == id); } }

Step 3: Create the Controller

Now, let’s create a controller to handle HTTP requests. Create a new folder called Controllers, and add a BooksController.

// Controllers/BooksController.cs using Microsoft.AspNetCore.Mvc; using MyRestfulApi.Data; using MyRestfulApi.Models; namespace MyRestfulApi.Controllers { [Route("api/[controller]")] [ApiController] public class BooksController : ControllerBase { private readonly BookStore _bookStore = new BookStore(); // GET: api/books [HttpGet] public ActionResult<IEnumerable<Book>> GetBooks() { return Ok(_bookStore.GetAllBooks()); } // GET: api/books/{id} [HttpGet("{id}")] public ActionResult<Book> GetBook(int id) { var book = _bookStore.GetBookById(id); if (book == null) { return NotFound(); } return Ok(book); } // POST: api/books [HttpPost] public IActionResult AddBook([FromBody] Book book) { if (!ModelState.IsValid) { return BadRequest(ModelState); } _bookStore.AddBook(book); return CreatedAtAction(nameof(GetBook), new { id = book.Id }, book); } // PUT: api/books/{id} [HttpPut("{id}")] public IActionResult UpdateBook(int id, [FromBody] Book book) { if (id != book.Id || !ModelState.IsValid) { return BadRequest(); } _bookStore.UpdateBook(book); return NoContent(); } // DELETE: api/books/{id} [HttpDelete("{id}")] public IActionResult DeleteBook(int id) { _bookStore.DeleteBook(id); return NoContent(); } } }

Running the API

Now that we've set up our project, models, data storage, and controller, let's run the API. Navigate to your project root in the terminal and execute:

dotnet run

You can then test the endpoints using Postman or any other API testing tool:

  • GET http://localhost:5000/api/books – Retrieves a list of books.
  • GET http://localhost:5000/api/books/1 – Retrieves a book with ID 1.
  • POST http://localhost:5000/api/books – Adds a new book. Example body:
    { "Title": "Fahrenheit 451", "Author": "Ray Bradbury" }
  • PUT http://localhost:5000/api/books/1 – Updates the book with ID 1. Example body:
    { "Id": 1, "Title": "Nineteen Eighty-Four", "Author": "George Orwell" }
  • DELETE http://localhost:5000/api/books/1 – Deletes the book with ID 1.

Popular Tags

ASP.NET CoreRESTful APIsWeb Development

Share now!

Like & Bookmark!

Related Collections

  • Mastering .NET Core: Essential Concepts

    19/09/2024 | DotNet

  • .NET Core Performance Mastery: Optimizing for Speed and Efficiency

    09/10/2024 | DotNet

  • Microservices Architecture with .NET Core

    12/10/2024 | DotNet

Related Articles

  • Building a Console Application in .NET Core

    19/09/2024 | DotNet

  • Mastering Memory Management and Garbage Collection in .NET Core

    09/10/2024 | DotNet

  • Parallel Programming and Threading Optimization in .NET Core

    09/10/2024 | DotNet

  • Unlocking Performance

    09/10/2024 | DotNet

  • Entity Framework Core Performance Tuning

    03/09/2024 | DotNet

  • Implementing the API Gateway Pattern in .NET Core Microservices

    12/10/2024 | DotNet

  • Efficient Use of Span<T> and Memory<T> in .NET Core

    09/10/2024 | DotNet

Popular Category

  • Python
  • Generative AI
  • Machine Learning
  • ReactJS
  • System Design