rhondamuse.com

Creating a RESTful API with ASP.NET Core in .NET 8

Written on

To construct a RESTful Web API with ASP.NET Core in .**NET 8.0**, this guide will walk you through the necessary steps.

As the latest Long Term Support (LTS) version, .NET 8 will be supported until November 10, 2026.

This API will manage movie data stored in a relational database, specifically SQL Server, as shown in the table below:

The topics covered in this article include: 1. Understanding REST 2. Starting a Web API Project 3. Adding a Model 4. Setting Up a Database Context 5. Creating the Database with Migrations 6. Developing API Controllers and Methods

Before we begin, ensure you have the following tools installed: 1. Visual Studio 2022 2. .NET 8.0 SDK 3. Microsoft SQL Server Express

Let’s dive in!

  1. Understanding REST

REST, or Representational State Transfer, is an architectural style for designing RESTful APIs. It facilitates standardized communication between systems on the web, allowing for seamless interactions. REST follows a client-server model, enabling independent evolution of both applications without dependencies.

Key features of REST include statelessness, meaning all necessary information for a request is included in the communication without relying on server-side session states. Additionally, REST promotes a uniform interface among components, exposing resources through URIs that resemble directory structures.

Though not limited to HTTP, REST is frequently associated with it. In HTTP, four main verbs dictate resource interactions in a RESTful system: 1. GET: Retrieve a specific resource (by id) or a collection. 2. POST: Create a new resource. 3. PUT: Update a specific resource (by id). 4. DELETE: Remove a specific resource by id.

Data representations in REST often involve JSON or XML to describe data objects and their properties. Owing to its simplicity, REST has largely replaced SOAP-based interface designs, leaving a lasting impact on web development.

Having covered the basics of REST, let’s move on to the implementation phase.

  1. Starting a Web API Project

Open Visual Studio 2022 and follow these steps to initiate a new project: 1. Launch Visual Studio 2022. 2. Select "Create a new project." 3. In the project creation window, search for ASP.NET Core Web API. 4. Choose ASP.NET Core Web API as the template. 5. Click on the Next button to continue.

On the subsequent screen: 1. Select .NET 8.0 as your target framework. 2. Click the Create button to set up your ASP.NET Core Web API project with the specified framework version.

Now, you have a starter project set up:

In the Program.cs file, you’ll notice that Swagger support is automatically added to your project.

Also, observe that the Swashbuckle.AspNetCore NuGet package has been included as a dependency. For more details on Swagger, consult the ASP.NET Core Web API documentation regarding Swagger / OpenAPI.

Next, run the project using ctrl+f5. When the browser opens and displays the Swagger UI, navigate to the WeatherForecast section, select the GET method, click Try It Out, and then hit Execute to view the default output.

The default URL is derived from the configurations specified in the launchSettings.json file.

The values you see are generated by the GET method in the WeatherForecastController.

These values are hardcoded with some randomness in the WeatherForecastController. In the upcoming steps, we'll add functionality to our Web API to manage records in an SQL Server database, allowing us to create, view, update, and delete through REST API endpoints.

  1. Adding a Model

To create a class in the Movie Models folder: 1. In Solution Explorer, right-click on the project. 2. Select Add -> New Folder and name it Models. 3. Right-click the newly created Models folder. 4. Select Add -> Class. 5. Name the class Movie.cs and click Add.

Now, add the following properties to the Movie class:

The Id field is essential for the database as the primary key.

Entity Framework Core

We will utilize our model with Entity Framework Core (EF Core) to interact with a database.

EF Core is an object-relational mapping (ORM) framework that simplifies data access code. Model classes are independent of EF Core; they merely define the properties of the data stored in the database.

We’ll start by creating the model classes, and EF Core will generate the database. This approach is known as the Code-First Approach.

  1. Setting Up a Database Context

The database context class is crucial for coordinating Entity Framework functionality for a data model. It is created by inheriting from the Microsoft.EntityFrameworkCore.DbContext class.

Now, right-click the Models folder and select Add -> Class. Name the class MovieContext and click Add. Then, insert the following code into the class:

The above code establishes a DbSet<Movie> property representing the entity set. In EF terminology, an entity set typically corresponds to a database table, while an entity corresponds to an individual row within that table.

The connection string’s name is passed to the context through a method call on a DbContextOptions object. During local development, the ASP.NET Core configuration system retrieves the connection string from the appsettings.json file.

We need to add our connection string to the appsettings.json file. I will use the local SQL server instance on my machine, and the connection string can be defined as follows:

Dependency Injection

Dependency Injection is a core principle in ASP.NET Core, around which the framework is built. During application startup, services, including the EF Core DB context, are registered with Dependency Injection. Components that require these services receive them through constructor parameters.

Next, we will register our database context in the built-in Inversion of Control (IoC) container. Add the following code in Program.cs:

  1. Creating the Database with Migrations

Next, we’ll create the database using the EF Core Migrations feature.

Migrations enable us to build a database reflecting our data model and modify the database schema as our data model changes.

First, we will add an initial Migration. Open Tools -> NuGet Package Manager -> Package Manager Console (PMC) and run the following command:

Add-Migration Initial

The Add-Migration command generates code to create the initial database schema based on the model defined in the MovieContext class. The Initial argument is the migration name, which can be anything.

After running the command, a migration file will be created in the Migrations folder:

Next, execute the following command in the PMC:

Update-Database

The Update-Database command invokes the Up method in the Migrations/{time-stamp}_Initial.cs file, which creates the database.

Now, let’s check the created database. Open View -> SQL Server Object Explorer.

As you can see, the Movie table and the Migrations History table are automatically created. A record is also added to the migration history table, documenting the migrations executed on the database.

  1. Developing API Controllers and Methods

In this section, we’ll create the Movies API Controller, introduce the relevant methods, and test them.

First, let’s add the controller. Right-click on the Controller folder and select Add -> Controller.. and then choose API Controller — Empty:

Click Add and give your controller a name on the next screen.

The MoviesController is created as follows:

Notice that the class is annotated with the [ApiController] attribute, indicating that it is designed to handle web API requests.

The MoviesController class inherits from ControllerBase.

Next, we will inject the database context mentioned previously through the controller's constructor. Add the following code:

Now, we will add CRUD (create, read, update, and delete) action methods to the controller, starting with the GET methods.

GET Method

The GetMovies method retrieves all movies, while the GetMovie(int id) method returns the movie corresponding to the specified Id. Both methods are marked with the [HttpGet] attribute, indicating they respond to HTTP GET requests.

These methods establish two distinct GET endpoints: 1. GET /api/Movies 2. GET /api/Movies/{id}

To test the application, you can access the two endpoints from a browser using the following URLs: 1. https://localhost:{port}/api/movies 2. https://localhost:{port}/api/movies/{id}

The return type of the GetMovie methods is ActionResult<T>. ASP.NET Core automatically serializes the object to JSON and includes it in the response message body. The response code for this type is 200, assuming there are no unhandled exceptions. Any unhandled exceptions are converted into 5xx errors.

Routing and URL Paths

Each method's URL path is constructed as follows: 1. Start with the template string in the controller’s Route attribute (Route(“api/[controller]”)). 2. Replace [controller] in the template with the name of the controller, following the convention of the controller class name without the Controller suffix. In this instance, the controller class name is MoviesController, thus the controller name is movies. 3. ASP.NET Core routing is case insensitive.

Testing the GetMovie Method

Navigate to the SQL Server Object Explorer, right-click the Movies table, and choose View Data:

Now, you can test the GET endpoints by launching the application with the Start (Ctrl+F5) command.

Then, select the second GET method, click Try it out, input one of the IDs mentioned earlier into the id field, and click Execute.

If no item matches the requested Id, the method will return a 404 NotFound error.

POST Method

Add the following code to the MoviesController:

The PostMovie method creates a movie record in the database. This code snippet represents an HTTP POST method, indicated by the [HttpPost] attribute. This method retrieves the movie record’s value from the body of the HTTP request.

The CreatedAtAction method performs the following: 1. Returns an HTTP 201 status code upon success. HTTP 201 is the standard response for an HTTP POST method that creates a new resource on the server. 2. Adds a Location header to the response, indicating the URI of the newly created movie record. 3. Uses the GetMovie action to construct the URI for the Location header.

Testing the PostMovie Method

Start the application and select the POST method in the Movies section.

Click Try it out and input the movie details you wish to add in the request body:

Then click Execute.

The response status code is 201 (Created), and a location header is included in the response:

You can also verify this record in the Movies table in your local database:

PUT Method

Add the following code to the MoviesController:

The PutMovie method updates the movie record corresponding to the provided Id in the database. This code snippet signifies an HTTP PUT method, marked by the [HttpPut] attribute. This method extracts the movie record’s value from the body of the HTTP request. It is crucial to provide the Id in both the request URL and the body, ensuring they align. According to HTTP specifications, a PUT request requires the client to transmit the complete updated entity, not just the changes.

Upon successful execution, the response will be 204 (No Content).

Testing the PutMovie Method

Click Execute.

You should see the updated information in the database:

If you attempt to update a record that does not exist in the database, you will receive a 404 Not Found error.

DELETE Method

Add the following code to the MoviesController:

The DeleteMovie method deletes the movie record with the specified Id from the database. This code snippet indicates an HTTP DELETE method, marked by the [HttpDelete] attribute. This method expects the Id in the URL to identify the movie record slated for removal.

Testing the DeleteMovie Method

Start the application and select the DELETE method in the Movies section.

Click Try it out and input the Id of the movie you wish to delete in the id field:

Then click Execute.

There is no need to provide a request body for this operation. The response status is 204 No Content, indicating successful execution of the delete operation.

You can also verify from the database that the record has been deleted:

The complete source code can be found here:

GitHub - CSSinghNet/AspNetCoreWebAPI8: Create a RESTful Web API using ASP.NET Core in .NET 8.0…

I hope you found this article useful.

Thank you for reading!

Related Tags:

Share the page:

Twitter Facebook Reddit LinkIn

-----------------------

Recent Post:

Journey Through Shadows: Alex's Quest for Mental Wellness

Explore Alex's journey through mental health challenges, creativity, and the pursuit of understanding and healing.

Dart and Flutter Terminology: A Comprehensive Guide

Explore essential Dart and Flutter terms with clear explanations for beginners in mobile app development.

How I Allegedly Turned $150,000 into $1,500,000 in Crypto

A humorous take on a fictional journey into cryptocurrency investment, exploring the highs and lows of chasing wealth in the DeFi space.

Endangered Majesty: Discover the Black Rhinoceros, Nature's Iconic Survivor

Explore the Black Rhinoceros, a magnificent yet endangered species, and learn about its habitat, behavior, and conservation efforts.

Embrace Life's Flow: Transforming Struggles into Serenity

Discover how acceptance, mindfulness, and gratitude can help you stop resisting life and start flowing with its natural currents.

Harnessing AI to Enhance Writing Productivity and Precision

Discover how AI can boost writing efficiency and accuracy while addressing common challenges.

# Essential Parenting Practices for Raising Healthy Adults

Explore fundamental practices to ensure your child grows into a well-adjusted adult, emphasizing respect, communication, and accountability.

Empowering Choices: The Importance of Saying No

Explore the significance of knowing when to say no in business and life, enhancing credibility and personal values.