10 Steps To Master Web API with ASP.NET CORE & EF Core

May 6, 2020
Technology
1 0

Step by Step Learn, how to design a Web API with ASP.NET Core in Visual Studio using Code-First Approach, Entity Framework and Swagger

Hello everyone, we are going to create a Web API with ASP.NET CORE step by step with Code-First approach using Entity Framework and later, we will test the same API using Swagger. If some of the terms are new to you, don’t worry, I will explain the basic terms before we jump into the code, so that you have a clear understanding of the concepts, how it works.

Let’s design a Web API with ASP.NET CORE Step by Step with Code-First approach using Entity Framework from inception to implementation.

Introduction to Web API with ASP.NET CORE

As we discussed, we will be designing a brand-new Web API with ASP.NET CORE. Here are some technical terms you need to aware of before we start on the code part. Let’s discuss them one by one. We will be using Visual Studio 2017 (15.9), .Net Core and Entity Framework 6. If you don’t have Visual studio IDE (Integrated Development environment) installed, it’s available to download free on https://visualstudio.microsoft.com/.

What is an API and Why do we need it?

API stands for Application Programmable Interface. Before we conclude the definition, Let’s understand what that means with a few real-world examples.

Let’s assume you want to book an air travel from New York to Los Angeles, California and instead of trying to search for a specific airline, you decided to search on a travel website or say, https://google.com/flights which gives you results from multiple airlines. As you know, Google doesn’t own these Airlines database but still get information which is relevant for the customers and provide this information on an interface upon user request. Behind the scene, the mechanism which brings this information from Airline databases is accomplished by an API

  • which send requests to multiple sources by passing certain information (from, to, dates)
  • and in return gets the list of available flights
  • consolidate the information from one or more sources and present it to customer in a single screen.
Multiple flights results returned by an API

Why do we need it? API, Application Programming Interface is a service that can be used by various apps at the client-side by a wide range of clients including browsers, mobiles, tablets or IOT (Internet of things) devices to retrieve and update information.

So, when you want to target wide range of clients over HTTP, ASP.NET WEB API is the best choice. You can create a restful Web API with ASP.NET CORE, which can communicate with the clients using HTTP and cater any browser and almost any device. Web API enables you to perform all the CRUD operations using HTTP verbs as below:

GET – Get all the records or specific record, if Id is passed as input

PUT – Updates a particular record

DELETE – Delete a record

POST – Insert a new record

Let’s jump into the real thing, where we will design a brand new Web API with ASP.NET CORE step by step using Visual Studio 2017, Code-First approach along with Entity Framework.

Create a Web API with ASP.NET CORE in Visual Studio

  1. Open Visual Studio in administrator mode and go to File -> New -> Project (Ctrl + Shift + N)
  2. Select Web in the left templates and ASP.NET Core Web Application in the right. Give any name for your project and save on a desired location in your system.

3. Once you hit OK, you will be presented with a new screen for selecting the application templates, Select API, un-check Configure for Https, keep No Authentication as it is and click OK

Web API project template

4. First install these 3 packages from NuGet Package manager.

  • Microsoft.EntityFrameworkCore(2.2.6)
  • Micorosft.EntityFrameworkCore.SqlServer
  • Swashbuckle.AspNetCore

Right click on Project and click on Manage NuGet Packages. NuGet is a free and open source visual studio integrated extension where you can find, consume and use the packages in your project.

Entity Framework is an Object Relational Mapper or ORM in short, which maps .NET Objects and database and eliminate the need of data access code.

Start with Model classes

Right click on the Project and add a new folder Models and then add a new class Category in it.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebAPI.Models
{
    public class Category
    {
        public int Id { get; set; }

        public string CategoryName { get; set; }
    }
}

Adding Controller and DbContext

It’s time to add a controller, so let’s right click on Controllers folder and add a new controller. Select the option to create an API Controller with actions, using Entity Framework and click on Add

Add API Controller with scaffolding

In the popup window, Select the Model class (Category from Models), Keep the Controller name as it is (CategoryController.cs) and for DataContext, since, we don’t have any Context file, we will be creating a new data context, Click on the + button and then Click Add.

Add Db Context while creating a controller

      So, what exactly happened?  

  • WebAPIContext class inherited by DbContext was added in \Data folder.
  • WebAPIContext class was registered in startup.cs
  • CategoryController.cs was added in Controllers folder with all the CRUD operations.

Register swagger in Web API with ASP.NET CORE and add related configurations

There are few more settings we need to do to make the process easy to understand.

  • First, change the database name, you can update it in appsettings.json
  • Second, change the default controller to”launchUrl”: “swagger“, in launchsettings.json
  • Register the swagger in startup.cs

Migrations in package manager console

Now we have the basic structure ready and it’s time to learn some magic here with code-first migrations. We will be using package manager console to run the migration commands.

Package Manager Console is a PowerShell window integrated with Visual Studio IDE to run commands related to NuGet, Migrations and many more. You can open Package Manager Console by going the path below.

                        Tools -> Library Package Manager -> Package Manager Console

There are few mostly used commands.

PM> get-help migration

  • Gives a list of commands related to migration activities

PM> Add-Migration FirstCreateDatabase

  • To add a migration

PM> Update-database

  • To update the database

Now, we have the Model class ready, also we have created a WebAPIContext class inherited from DbContext class too, it’s time to run the migrations, which will create the database

Running migration commands in Package Manager Console

Verify Database and run the application using swagger

So, what is the outcome of above step:

  • A Migration file will be created in Migrations folder by the first command.
  • Database created in (localdb)\mssqllocaldb and you can verify the database in View -> SQL Server Object Explorer
Database created

Let’s run the project (F5) and verify with Swagger.

Swagger is an open source framework to design, build, consume, test & document the RESTful APIs.

Swagger display Category controller CRUD operations

Adding more Model classes and define one-to-many relationships

Let’s extend the project by adding one more class say ‘Product.cs’. Basically, we will be creating a new class which will have a one-to-many relationship with Category. So, one category can have multiple products associated to it. For that, we have to add a foreign key reference of CategoryId in Product.cs class. You can add this in step 3 (when we added the Category.cs class in Models). I added Product.cs to showcase that we can run Migration commands again to alter the database or to add new objects.

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;

namespace WebAPI.Models
{
    public class Product
    {
        public int Id { get; set; }
        public string ProductName { get; set; }
        public decimal Price { get; set; }


        public int CategoryId { get; set; }

        [JsonIgnore]
        [ForeignKey("CategoryId")]
        public Category Category { get; set; }
    }
}

Rebuild the solution (Ctrl + Shift + B) and add Product Controller just like we added Category controller in Step 4.

Add New Controller
Adding Product controller

Web API Context gets updated with the Product DbSet.

WebAPIContext class with Product DbSet

Run another migration for creating Product table from Product.cs model class.

Migration for Product.cs

Unit Test the API with Swagger with CRUD operations

Run the project and let’s see if we have got Products CRUD too in the swagger.

Swagger with Category and Products
GET Categories – Brings all the categories
  • Click on Get category and expand the accordion.
  • Click on Try It Out button
  • Click on Execute button

This brings you all the available categories in JSON format in the Response section. If you see a blank value, that means there are no records for Categories.

Response Code 200 – OK means, the request was processed successfully and a response was provided.

POST Category – Insert a new record into Category table
  • Click on POST category and expand the accordion.
  • Click on Try It Out button
  • Change the Category text. Don’t change the Id part.
  • Click on Execute button

This brings you the latest category inserted in the Response section.

Response Code 201 – means, the request was processed and a record was inserted successfully.

Response Code 204 – Conflict means, there is already a category exists with the same name and would not allow the duplicate insert.

Post Category Response
GET Category By Id – To fetch the Category based on ID
  • Click on Get category By Id and expand the accordion.
  • Click on Try It Out button
  • Enter any value in Id
  • Click on Execute button

Response Code 200 – means, the request was processed and a record was found and returned in Response..

Response Code 404- Not Found means, there is no record found for the Category Id

As simple as that, You need to pass an Id and it will return the Category object, if the Id exists and it will return blank, if there is no record found for the Id.

PUT Category – Updating a Category
  • Click on PUT category expand the accordion.
  • Click on Try It Out button
  • Enter value in Id
  • Enter the existing Id and new CategoryName you want to update
  • Click on Execute button

Response Code 204 – means, the request was processed and a record was updated and returned in Response..

Response Code 404- Not Found means, there is no record found for the Category Id

DELETE Category – Removing a Category
  • Click on Delete category & expand the accordion.
  • Click on Try It Out button
  • Enter value in Id
  • Click on Execute button

Response Code 200 – means, the request was processed and a record was Deleted and returned in Response..

Response Code 404- Not Found means, there is no record found for the Category Id

Summary

In the article above, we learnt how to create a Web API with ASP.NET CORE using Code-first Approach & Entity Framework core. If you have a question regarding the article above, please feel free to comment below. I hope this helps you to give you a start to design more robust Web API with ASP.NET CORE in future.

Articles you might like:

Step By Step Guide To Remove Bitnami Banner From Your Website

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *