Tutorial .Net Core 3.1 First Web API for beginners

Alpesh Patel
C# Programming
Published in
7 min readJun 16, 2021

In this tutorial we are going to learn first Web API using ASP.Net Core using core 3.1. I am going to develop a sample application for an inventory REST service with basic operations.

Web API from ASP.NET Core is the same as the one from ASP.NET Core MVC. The Web API offers a simple communication way based on Representational State Transfer (REST). With REST, HTTP verbs such as GET, POST, PUT, and DELETE is used. GET is used to retrieve resources, POST is used to add new resources, PUT is used to update resources, and DELETE is used to delete resources.

Prerequisites

The following must be installed in your system:

Step 1 New Project

Once you have installed the Visual Studio 2019 and .Net Core 3.1 SDK, you can start building a new ASP.NET Core Web API.

  • Open VS2019
  • On the start page, choose Create a new project.
  • Create a web app and From the Visual Studio select Create a new project. Select ASP.NET Core Web Application > Next.
  • Give your project a name i.e. SimpleDotNetCoreWebAPI and give your project a location where it’ll be saved and click Create.
  • Now, you need to choose the framework version and API project Template:
  • After click on create button, you can see your API project is created and opened.

Step 2 Run Project

  • The project template creates a WeatherForecast API. Call the Get method from a browser to test the app.
  • You can setup your start up URL from “launchsettings.json” as below:

Step 3 Add Model Class

  • A model is a set of classes that represent the data that the app manages. The model for this app is a single TodoItem class.
  • First add Models folder in your solutions using right-click the project. Select Add > New Folder. Name the folder Models.
  • Now, Add new class with name “TodoItem”, using Right-click the Models folder and select Add Class.
  • Replace the template code with the following code:

Step 4 Add the TodoContext database context

  • The database context is the main class that coordinates Entity Framework functionality for a data model. This class is created by deriving from the Microsoft.EntityFrameworkCore.DbContext class.
  • Let’s Add NuGet packages:
    From the Solution right click on dependency, select Manage NuGet Packages.
  • Select the Browse tab, and then enter Microsoft.EntityFrameworkCore.SqlServer in the search box, select Latest Stable Version and Install.
  • Install same “Microsoft.EntityFrameworkCore.InMemory”
  • Now it is ready for add database context: Right-click the Models folder and select Add > Class. Name the class TodoContext and click Add.
  • Change code in TodoContext.cs as following:
  • In ASP.NET Core, services such as the DB context must be registered with the dependency injection container. The container provides the service to controllers.
  • Update Startup.cs with the following highlighted code:

Step 5 Add Controller

  • We will use Scaffold for add controller as below steps:
  • Right-click the Controllers folder, Select Add > New Scaffolded Item and Select API Controller with actions, using Entity Framework, and then select Add.

Now, In the Add API Controller with actions, using Entity Framework dialog:

  • Select TodoItem (SimpleDotNetCoreWebAPI.Models) in the Model class.
  • Select TodoContext (SimpleDotNetCoreWebAPI.Models) in the Data context class.
  • Select Add.
  • You can see your controller is created with default all Get, Put and Post request methods:

Step 5 Install Postman

What is Postman? Postman is a popular API client that makes it easy for developers to create, share, test and document APIs. This is done by allowing users to create and save simple and complex HTTP/s requests, as well as read their responses. The result — more efficient and less tedious work.

Install Postman from here: https://www.postman.com/downloads/

Complete follow the following steps after install Postman:

  • Start the web app.
  • Start Postman.
  • Disable SSL certificate verification
  • From File > Settings (General tab), disable SSL certificate verification.

Post methods:

Now run your project, open Postman and Create a new request and follow steps:

  • Set the HTTP method to POST.
  • Set the URI to https://localhost:<port>/api/TodoItems. For example, https://localhost:5001/api/TodoItems.
  • Select the Body tab.
  • Select the raw radio button.
  • Set the type to JSON (application/json).
  • In the request body enter JSON for a to-do item and Select Send.
  • Response look like this:
  • Return values
  • The return type of the GetTodoItems and GetTodoItem methods is ActionResult<T> type. ASP.NET Core automatically serializes the object to JSON and writes the JSON into the body of the response message. The response code for this return type is 200, assuming there are no unhandled exceptions. Unhandled exceptions are translated into 5xx errors.
  • ActionResult return types can represent a wide range of HTTP status codes. For example, GetTodoItem can return two different status values:
  • If no item matches the requested ID, the method returns a 404 NotFound error code.
  • Otherwise, the method returns 200 with a JSON response body. Returning item results in an HTTP 200 response.

GET methods:

These methods implement two GET endpoints:

  • GET /api/TodoItems
  • GET /api/TodoItems/{id}

Test the app by calling the two endpoints from a browser or Postman. For example:

If you want to get data with filter for example you want to get pacific Id record then you can use. In the HTTP Get method, “{id}” is a placeholder variable for the unique identifier of the to-do item. When GetTodoItem is invoked, the value of “{id}” in the URL is provided to the method in its id parameter.

Put Method:

If you want to update record the you can use HTTPPut request:

  • Examine the PutTodoItem method:

PutTodoItem is similar to PostTodoItem, except it uses HTTP PUT. The response is 204 (No Content). According to the HTTP specification, a PUT request requires the client to send the entire updated entity, not just the changes. To support partial updates, use HTTP PATCH.

  • The following image shows the Postman update:

Delete Method

  • If you want to delete record the you can use HTTPDelete request:

Test the DeleteTodoItem method, Use Postman to delete a to-do item:

Thank you for reading, please let me know your questions, thoughts, or feedback in the comments section. I appreciate your feedback and encouragement.

Keep Learning…. !!!

--

--

Alpesh Patel
C# Programming

Technology Specialist and Full-Stack Developer. Find me on linkedin for more details https://www.linkedin.com/in/alpesh-patel-8b930952