Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Web API with .NET Core 3.1 from Scratch. Making a To-Do App — Part 1

Web API with .NET Core 3.1 from Scratch. Making a To-Do App — Part 1

Introduction

If you are new to Web APIs, this note will serve you well because we are going to see the fundamentals of Web Api with .NET Core from scratch.

This guide will help you navigate learning how to make a Web API for a simple app, consume it and add a design to it. It provides learning resources that I found effective in the official documentation, along with supplementary explanations and my practices.

To keep this guide digestible, I broke it up into three parts. Part one goes over the creation of a Web Api using .NET Core and testing it with Postman. Part two goes over consuming the Web API using Javascript. Part three goes over adding a design to the app with Boostrap 4. If you’re familiar with Boostrap 4 or you want to use another library for the design you can skip part three which covers Boostrap 4.

Photo by Shahadat Rahman on Unsplash

What’s a Web API?

Before we understand what is Web API, let’s see what is an API (Application Programming Interface).

As per Wikipedia’s Definition of API

An application programming interface (API) is a computing interface to a software component or a system, that defines how other components or systems can use it. It defines the kind of calls or requests that can be made, how to make them, the data formats that should be used, the conventions to follow, etc. It can also provide extension mechanisms so that users can extend existing functionality in various ways and to varying degrees.

For simplicity, API is an interface with a set of functions for developers to access specific features or data of an application, operating system or other services.

The Web API is a type of API that can be accessed over the web using the HTTP protocol. It is necessary to understand that it is only a concept, it is not a technology. To use it in a technology, we must build both the API and a website that consumes that API.

Pre-Requisites

  • Visual Studio 2019 16.4 or later with the ASP.NET and web development workload or Visual Studio Code
  • .NET Core 3.1 SDK or later
  • Postman

Step 1: Create a web API project.

If you are using Visual Studio Code, do this:

  • Open the integrated terminal.
  • Change directories (cd) to the folder that will contain the project folder.
  • Run the following commands:
dotnet new webapi -o TodoApi
cd TodoApi
dotnet add package Microsoft.EntityFrameworkCore.SqlServer 
dotnet add package Microsoft.EntityFrameworkCore.InMemory 
code -r ../TodoApi

This commands creates a webapi application called TodoApi and adds the necessary SQL Server and InMemory packages for its use.

When a dialog box asks if you want to add required assets to the project, select Yes.

The preceding commands:

  • Creates a new web API project and opens it in Visual Studio Code.
  • Adds the NuGet packages which are required in the next section.

If you are using Visual Studio, do this:

  • From the File menu, select NewProject.
  • Select the ASP.NET Core Web Application template and click Next.
  • Name the project TodoApi and click Create.
  • In the Create a new ASP.NET Core Web Application dialog, confirm that .NET Core and ASP.NET Core 3.1 are selected. Select the API template and click Create.

Step 2: Add a model class and a database context.

First for all, What is a Model Class and why we need it?

The model represents domain-specific data and business logic within the MVC architecture. From the Model class, model objects retrieve and store the state of the model in the persistence store as a database. The model class also contains data in public properties and in both the MVC architecture and the .NET Core MVVC architecture, the Model classes reside in the Model folder in the project folder structure.

We need this because the model is responsible for maintaining the application data. Without that, we can’t apply any arquitecture.

Second of all, what is a database context and why we need it?

Phrasing Microsoft

A DbContext ( database context) instance represents a combination of the Unit Of Work and Repository patterns such that it can be used to query from a database and group together changes that will then be written back to the store as a unit. DbContext is conceptually similar to ObjectContext.

In summary, dbContext are a set of objects that can query a database and group the changes that are made in it.

We need dbContext to be able to make the changes in a grouped way in a database and to consult the changes in it in an optimized (grouped) and updated way.

If you are using Visual Studio, do this:

  • In Solution Explorer, right-click the project. Select Add > New Folder. Name the folder Models.
  • Right-click the Models folder and select Add > Class. Name the class TodoItem and select Add.
  • Replace the template code with the following code:
public class TodoItem
{
public long Id { get; set; }
public string Name { get; set; }
public bool IsComplete { get; set; }
}

In you are using Visual Studio Code / Mac, do this:

  • Add a folder named Models.
  • Add a file namedTodoItem.cs to the Models folder with the following code:
public class TodoItem
{
public long Id { get; set; }
public string Name { get; set; }
public bool IsComplete { get; set; }
}

Step 2.A. Add Microsoft.EntityFrameworkCore.SqlServer

  • ONLY in Visual Studio: Go from the Tools menu, select NuGet Package Manager > Manage NuGet Packages for Solution.
  • Select the Browse tab, and then enter Microsoft.EntityFrameworkCore.SqlServer in the search box.
  • Select Microsoft.EntityFrameworkCore.SqlServer in the left pane.
  • Select the Project check box in the right pane and then select Install.
  • Use the preceding instructions to add the Microsoft.EntityFrameworkCore.InMemory NuGet package.

Step 2.B. Add the TodoContext database context

  • If you are using Visual Studio Code / Mac : Add a file named TodoContext.cs into the Models folder.
  • In you are using Visual Studio: Right-click the Models folder and select Add > Class. Name the class TodoContext and click Add to create and start writting the class.
using Microsoft.EntityFrameworkCore;
namespace TodoApi.Models
{
public class TodoContext : DbContext
{
public TodoContext(DbContextOptions options)
: base(options)
{
}
        public DbSet TodoItems { get; set; }
}
}

Step 2.C: Register the database context

In ASP.NET Core, services such as the DB context must be registered with the dependency injection (DI) container. The function of the container is provide the service to controllers.

Update Startup.cs with the following highlighted code

The preceding code:

  • Adds the database context to the DI container.
  • Specifies that the database context will use an in-memory database.

Step 3: Scaffold a controller with CRUD methods.

What is Scaffolding and why we need it?

Basically, it is a way to generate automatically some of the parts of a project, like models, controllers and views. Although the scaffolder generates most of the necessary code, you need to update your project to complete the process.

We need it because it saves a lot of time, in addition to automatically generating dependencies in the MVC model.

On Visual Studio Code, do this:

dotnet add package Microsoft.VisualStudio.Web.CodeGeneration.Design
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet tool install --global dotnet-aspnet-codegenerator
dotnet aspnet-codegenerator controller -name TodoItemsController -async -api -m TodoItem -dc TodoContext -outDir Controllers

The preceding commands:

  • Add NuGet packages required for scaffolding.
  • Installs the scaffolding engine (dotnet-aspnet-codegenerator).
  • Scaffolds the TodoItemsController.

On Visual Studio, do this:

  • Right-click the Controllers folder.
  • Select Add > New Scaffolded Item.
  • Select API Controller with actions, using Entity Framework, and then select Add.
  • In the Add API Controller with actions, using Entity Framework dialog:
  • Select TodoItem (TodoApi.Models) in the Model class.
  • Select TodoContext (TodoApi.Models) in the Data context class.
  • Select Add.

The generated code:

  • Marks the class with the [ApiController] attribute. This attribute indicates that the controller responds to web API requests. For information about specific behaviors that the attribute enables, see Create web APIs with ASP.NET Core.
  • Uses DI to inject the database context (TodoContext) into the controller. The database context is used in each of the CRUD methods in the controller.

The ASP.NET Core templates for:

  • Controllers with views include [action] in the route template.
  • API controllers don’t include [action] in the route template.

When the [action] token isn't in the route template, the action name is excluded from the route. That is, the action's associated method name isn't used in the matching route.

Step 4: Configure routing, URL paths, and return values.

Both Visual Studio and Visual Studio Code:

Replace the return statement in the PostTodoItem to use the nameof operator:

// POST: api/TodoItems
[HttpPost]
public async Task> PostTodoItem(TodoItem todoItem)
{
_context.TodoItems.Add(todoItem);
await _context.SaveChangesAsync();
//return CreatedAtAction("GetTodoItem", new { id = todoItem.Id }, todoItem);
return CreatedAtAction(nameof(GetTodoItem), new { id = todoItem.Id }, todoItem);
}

The preceding code is an HTTP POST method, as indicated by the [HttpPost] attribute. The method gets the value of the to-do item from the body of the HTTP request.

The CreatedAtAction method:

  • Returns an HTTP 201 status code if successful. HTTP 201 is the standard response for an HTTP POST method that creates a new resource on the server.
  • Adds a Location header to the response. The Location header specifies the URI of the newly created to-do item. For more information, see 10.2.2 201 Created.
  • References the GetTodoItem action to create the Location header's URI. The C# nameof keyword is used to avoid hard-coding the action name in the CreatedAtAction call.

Step 5: Run the web app.

On Visual Studio Code, do this:

Press Ctrl+F5 to run the app or type the following command on Terminal

dotnet run

If the browser doesn’t open, go to following URL: https://localhost:5001/.

On Visual Studio, do this:

Select the option “TodoApi” where it saids IIS Express to run the web app locally.

You would see the Debug Console Running. Do not close it yet.

Step 6: Call the web API with Postman.

This tutorial uses Postman to test the web API. It’s the same for Visual Studio and Visual Studio Code.

With the web app running, open Postman and disable. SSL certificate verification.

To disable it, go to File > Settings (General tab) and disable SSL certificate verification.

Test PostTodoItem with Postman

  • Create a new request and call it “Test”. You can also create a folder. I created one called “TodoApi”
  • Set the HTTP method to POST.
  • Select the Body tab, the raw radio button and set the type to JSON (application/json).
  • In the request body enter JSON for a to-do item:
{   
"name":"walk dog",
"isComplete":true
}

Add the URL in the send field using the local port shown by the terminal (in my case it was 5001) by typing the following line and click “Send”.

https://localhost:[port number]/api/TodoItems

You would receive the output with an ID number 1

In Headers you can also see the location

Test the location header URI

  • Select the Headers tab in the Response pane.
  • Copy the Location header value:
  • Set the method to GET and paste the URI (for example, https://localhost:5001/api/TodoItems/1 ) and select Send

You would get the data was post in the ID number 1

Now that we have the Web Api working, in part two we are going to add a web form that allows inserting, updating, deleting and consulting (known as CRUD operations) the data of the Web Api with Javascript and in the third part we will se how to add responsive design with Boostrap to it.

References

Microsoft, (2020, May 25) Tutorial: Create a web API with ASP.NET Core. Retrieved from https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-web-api?view=aspnetcore-3.1&tabs=visual-studio

Would you like to know more? Do you need our help? Contact Us!
www.quadiontech.com


Web API with .NET Core 3.1 from Scratch. Making a To-Do App — Part 1 was originally published in Quadion Technologies on Medium, where people are continuing the conversation by highlighting and responding to this story.



This post first appeared on Quadion Technologies, please read the originial post: here

Share the post

Web API with .NET Core 3.1 from Scratch. Making a To-Do App — Part 1

×

Subscribe to Quadion Technologies

Get updates delivered right to your inbox!

Thank you for your subscription

×