Click here to Skip to main content
14,236,179 members

A Step by Step Guide to Create ASP.NET Core Web API with Entity Framework Core, Swagger and Postman

Rate this:
4.76 (10 votes)
Please Sign up or sign in to vote.
4.76 (10 votes)
5 Jul 2019CPOL
Create ASP.NET Core Web API with Entity Framework & Code First Approach and run through Swagger & Postman

Introduction

This is my ASP.NET Core Web API Fundamentals article that will teach you how to build ASP.NET Core Web API with Entity Framework using Scaffolding features and Code First Approach. This article is helpful for beginners and intermediate .NET Developers/ Architects who have some knowledge of Web Development with ASP.NET because we'll be focusing on developing an ASP.NET Core Application with CRUD (Create, Read, Update and Delete) operations with Visual Studio 2017, and the entire cast of characters that support ASP.NET Core projects.

Background

ASP.NET Web APIs is a great framework provided by Microsoft for building any type of HTTP service. In this article, you will learn, how to:

  • Create a new Web API Project in ASP.NET Core
  • Add Model Classes
  • Use Entity Framework Core
  • Add Migrations to Scaffold code for DB operations
  • Create Controllers with all the CRUD operation methods using DBContext and Entity Framework Core
  • Add and Configure Swagger in ASP.NET Core
  • Use Swagger and Postman to test your Web API

We will be creating a simple application to perform CRUD operations for 2 tables 'Product' and 'Category'.

Step 1: Create a New Project

  • Open Visual Studio -> Click on File ->New Project

  • Select Visual C# from the Templates and Select ASP.NET Core Web Application.

  • Give any name to your application and select the location where you want to save your project in your local directory and click OK.
  • At the top, select .NET Core and ASP.NET Core 2.2.

  • Select the Template as 'API' and click OK.
  • Once you hit OK, a default application will be created.

Step 2: Add Model Classes

Stop Debugging and add a new folder to the project named as Models and add 2 classes in there - 'Product' & 'Category'.

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

namespace CoreWebApiDemo.Models
{
    public class Category
    {
        public int Id { get; set; }
        public string CategoryName { get; set; }
    }
}

Build your solution. (Ctrl + Shift + B)

Build Project and add another class as Product.cs in Models folder:

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

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

Save and build the solution.

So, most of the manufacturing work is done. Now, we will be moving towards the packaging section.

Step 3. Use Entity Framework Core

We can install entity framework using Nuget Packet Manager or Package Manager console.

First, right click on your project and click on Manage Nuget Packages...

  • Go to Browse tab
  • Search and install these 3 packages:
    • Microsoft.EntityFrameworkCore
    • Microsoft.EntityFrameworkCore.SqlServer
    • Microsoft.EntityFrameworkCore.SqlServer.Design

Step 4: Adding DB Context and Controllers

DbContext represents a session with the database which can be used to query and save instances of your entities to a database. DbContext is a combination of the Unit Of Work and Repository patterns.

Right click on Controllers folder to add a controller: Controllers -> Add -> controller

  • Select Model Class as Category
  • For Data Context class, it will be empty, click on + button to add a new DB context class. Click Add on the popup window and then click on Add button again.

What will happen next?

  • Visual Studio will start scaffolding the code:

  • appSettings.json will be updated automatically and prompt might appear to save the unsaved changes:

    A new Db connection string will be added to appSettings.json file:

    "ConnectionStrings": {
        "CoreWebApiDemoContext": "Server=(localdb)\\mssqllocaldb;
         Database=CoreWebApiDemoContext-9225644b-7c5e-44f3-8d39-e607e8d10ea0;
         Trusted_Connection=True;MultipleActiveResultSets=true"
      }
  • A new folder Data will be created, and a DbContext file named as CoreWebApiDemoContext will be generated inside Data folder.
  • Similary, add another controller for Product CRUD operations with scaffolding and entity framework options. Select existing DBContext file which we created as previous steps.

    Db Context file will get updated automatically.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.EntityFrameworkCore;
    using CoreWebApiDemo.Models;
    
    namespace CoreWebApiDemo.Models
    {
        public class CoreWebApiDemoContext : DbContext
        {
            public CoreWebApiDemoContext (DbContextOptions<CoreWebApiDemoContext> options)
                : base(options)
            {
            }
    
            public DbSet<CoreWebApiDemo.Models.Category> Category { get; set; }
    
            public DbSet<CoreWebApiDemo.Models.Product> Product { get; set; }
        }
    }

Step 5: Adding Migrations in Package Manager Console

The Package Manager Console is a PowerShell console within Visual Studio used to interact with NuGet and automate Visual Studio. You can access the Package Manager Console from within Visual Studio by going to Tools -> Library Package Manager -> Package Manager Console.

Or:

You can Type Package Manager Console and find in search options.

Type get-help migration and hit enter:

PM> get-help migration

Run another command add-migration in Package Manager console to add a new migration. We have to give a name to the migration.

PM> add-migration FirstMigrationToCreateDB
  • A Migration file will be generated to include all the Db operations like Creating DB based on connection string from appsettings.json, creating tables based on Models and all the relations between them based on Data annotations.

  • Next, run another command update-database, which will run this migration and execute DB script.
    PM> update-database
  • Verify Database and tables based on your connection string. Go to View -> SQL Server Object Explorer

Step 6. Add and Configure Swagger in ASP.NET Core

  • Right click on your project and click on Manage Nuget Packages and browse for Swashbuckle.AspNetCore
  • Install the latest version of Swashbuckle.AspNetCore

    In the Startup class, import the following namespace to use the Info class:

    using Swashbuckle.AspNetCore.Swagger;

    Add the Swagger generator to the services collection in the Startup.ConfigureServices method:

    services.AddSwaggerGen(c =>
              {
                  c.SwaggerDoc("v1", new Info { Title = "Core Web API", Version = "v1" });
              });
    

    In the Startup.Configure method, enable the middleware for serving the generated JSON document and the Swagger UI:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.HttpsPolicy;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Logging;
    using Microsoft.Extensions.Options;
    using Microsoft.EntityFrameworkCore;
    using CoreWebApiDemo.Models;
    using Swashbuckle.AspNetCore.Swagger;
    
    namespace CoreWebApiDemo
    {
        public class Startup
        {
            public Startup(IConfiguration configuration)
            {
                Configuration = configuration;
            }
    
            public IConfiguration Configuration { get; }
    
            // This method gets called by the runtime. 
            // Use this method to add services to the container.
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    
                services.AddDbContext<CoreWebApiDemoContext>(options =>
                        options.UseSqlServer(Configuration.GetConnectionString
                                            ("CoreWebApiDemoContext")));
                services.AddSwaggerGen(c =>
                {
                    c.SwaggerDoc("v1", 
                    new Info { Title = "Core Web API", Version = "v1" });
                });
            }
    
            // This method gets called by the runtime. 
            // Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
                else
                {
                    // The default HSTS value is 30 days. 
                    // You may want to change this for production scenarios, 
                    // see https://aka.ms/aspnetcore-hsts.
                    app.UseHsts();
                }
                // Enable middleware to serve generated Swagger as a JSON endpoint.
                app.UseSwagger();
    
                // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
                // specifying the Swagger JSON endpoint.
                app.UseSwaggerUI(c =>
                {
                    c.SwaggerEndpoint("/swagger/v1/swagger.json", "Core Web API");
                });
    
                app.UseHttpsRedirection();
                app.UseMvc();
            }
        }
    }

    Build & run your project and replace /api/values with /swagger in the URL.

Step 7. Use Swagger and Postman to Test Your Web API

Postman is a free API debugging tool. You can install it on your Chrome browser or Mac. Install it for Chrome from here:

After successful installation, open it and select HTTP method and enter the URL of your web API.

  • Select GET operation
  • Enter URL
  • Click SEND button
  • The Results will be displayed in the body section. Since we don't have any Category yet. The results are displayed as blank.

Let's try a POST (Insert a category)

Before we insert a new category through POSTMAN, update PostCategory method in Category Controller to have a prefix of [FromBody] in the parameter.

Open Postman, Change GET to POST, enter the URL, click on Body, Select raw & then select application/json.

In the body, enter Category object in the below format to insert a new category.

{
  "id": 0,
  "categoryName": "Electronics"
}

Click on SEND button and the newly created Category object with the ID value will be displayed in the result section.

Verify database if the record has been inserted:

Insert few more categories in the same way.

Now, try a GET operation in POSTMAN.

Similarly, you can perform CRUD operations for Products.

Let's grab the object JSON from Swagger and perform a POST into Products by POSTMAN.

Verify in Database product Table.

Thank you for your time. Hope this article is useful to gain some practical knowledge about Web API, ASP.NET CORE, Swagger and POSTMAN and will help you to build more applications.

History

  • 5th July, 2019: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

anuj vohra
Architect
United States United States
No Biography provided

Comments and Discussions

 
QuestionSOLVED 2: Script Identity Insert ON Pin
DumpsterJuice9-Jul-19 2:58
memberDumpsterJuice9-Jul-19 2:58 
AnswerRe: SOLVED 2: Script Identity Insert ON Pin
anuj vohra9-Jul-19 7:00
memberanuj vohra9-Jul-19 7:00 
QuestionSOLVED - Identity Insert Pin
DumpsterJuice9-Jul-19 2:50
memberDumpsterJuice9-Jul-19 2:50 
AnswerRe: SOLVED - Identity Insert Pin
anuj vohra9-Jul-19 3:43
memberanuj vohra9-Jul-19 3:43 
QuestionGREAT Article Pin
DumpsterJuice9-Jul-19 2:47
memberDumpsterJuice9-Jul-19 2:47 
AnswerRe: GREAT Article Pin
anuj vohra9-Jul-19 4:00
memberanuj vohra9-Jul-19 4:00 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Article
Posted 4 Jul 2019

Stats

8.8K views
136 downloads
25 bookmarked