(C# ASP.NET Core) Getting Started with Web Api

This tutorial starts with a beginner's introduction to the concept of web api. After that we create a basic structure of a project that will help us learn about various types of web api - which will be serially covered in the next coming tutorials.
(Rev. 19-Mar-2024)

Categories | About |     |  

Parveen,

What is a Web Api

Let us first understand the concept of Web Api. A web api is a function on the server side that returns data in a format such as json or xml. A web api function can be used to execute an update, delete, insert query - and it can then return a simple code for success or failure or could return the number of records affected. A web api is different from a ready-to-render html page - it returns raw data, instead. It is upto the calling application to use that data in whatever manner it wants. For example, a desktop application could use that data to populate a drop down, or populate a listview. Similarly, a mobile application might render that data through its own UI Elements.

A client can call a web api through a GET request. It can even call it through a POST request. A web api can accept parameters. The parameters can be sent as query strings or in the body of the message.

Video Explanation (see it happen!)

Please watch the following youtube video:

Setup a Web Api Project

Now we shall set a project for learning about the web api. This will be a basic setup. We shall keep adding api in the next upcoming tutorials.

First of all create a simple ASP.NET Core project, and open the solution explorer as you see here.

Add a folder called Models so that we can keep our model classes and db contexts in this folder.

Right click this folder and add a model class called Doctor.

Double click and open this file so that we can examine the model class. This class has three properties - ID is an auto generated property, fees is a numeric property and Name is a string type.

We have also added a DbContext class for database communication.

// Models -> Doctor.cs 
// Install-Package Microsoft.AspNetCore.Identity.EntityFrameworkCore 
// Install-Package Microsoft.EntityFrameworkCore.Sqlite 

// namespaces 
using Microsoft.EntityFrameworkCore;

using System.ComponentModel.DataAnnotations;

using System.ComponentModel.DataAnnotations.Schema;

namespace MyRazorApp.Models
{

  // model class 
  public class Doctor
  {

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public string Name { get; set; } = default!;

    public int Fees { get; set; }
  }

  public class MyApiContext : DbContext
  {

    public MyApiContext(DbContextOptions options) : base(options)
    {

    }

    // MUST be PLURAL 
    public DbSet<Doctor> Doctors { get; set; } = default!;

  }

}

Open the solution explorer locate the Index.cshtml file in the Pages folder. Double click and open it! As you can see this is a single file of some text. We are not likely to use this file anywhere in this chapter on Web Api. It has been added only as a website home page.

// Pages -> Index.cshtml 

@page

<h1>Welcome WebApi!</h1>

<p>
  This is a web api project.
</p>

Open the solution explorer again and locate the program.cs file.

Double click and open this file!

First we have listed two nuget packages that must be installed - one is for the Entity Framework Core, and the other is for Sqlite database.

Then we have configured the service for Sqlite database. Notice that the connection string is for using it as an in-memory database. This is nice for testing purposes.

After that we have added services for razor pages.

Then we have used the DbContext for adding some test data. The EnsureCreated method is for creating the database, and after that two records have been added for use in web api tutorials.

// program.cs 
// Install-Package Microsoft.AspNetCore.Identity.EntityFrameworkCore 
// Install-Package Microsoft.EntityFrameworkCore.Sqlite 
using Microsoft.EntityFrameworkCore;

using MyRazorApp.Models;

var builder = WebApplication.CreateBuilder();

// the database is created in memory 
builder.Services.AddDbContext<MyApiContext>(
    opt => opt.UseSqlite("DataSource=file:mem?mode=memory&cache=shared")
);

builder.Services.AddRazorPages();

var app = builder.Build();


// seed some test data 
using (var scope = app.Services.CreateScope())

{

  var services = scope.ServiceProvider;

  var ctx = services.GetRequiredService<MyApiContext>();

  ctx.Database.EnsureCreated();

  ctx.Doctors.Add(new Doctor() { Fees = 100, Name = "doc 1" });

  ctx.Doctors.Add(new Doctor() { Fees = 200, Name = "doc 2" });

  ctx.SaveChanges();

}

app.MapRazorPages();

app.Run();

And lastly, the application is run.

We can run the application to open the home page. This confirms that we have no compilation or other errors so far. We are now ready to add web api in the next tutorials.


This Blog Post/Article "(C# ASP.NET Core) Getting Started with Web Api" by Parveen is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.