What is API in ASP.NET c#?

HTTP is used for more than just providing web pages. HTTP is also a strong foundation for developing APIs that expose services and data. HTTP is a basic, adaptable, and pervasive protocol. Because almost every platform supports an HTTP library, HTTP services may reach many customers, including browsers, mobile devices, and classic desktop programs. ASP.NET Web API is a framework for creating web APIs built on top of the .NET Framework.

This tutorial on C# Web API is focused on guiding you through the complete fundamentals of the Web API. You will learn the functionalities of the API through the practical examples in this tutorial.

Post Graduate Program: Full Stack Web Development

in Collaboration with Caltech CTMEEnroll Now

What is API in ASP.NET c#?

What Is C# Web API?

What is API in ASP.NET c#?

ASP.NET Web API is a robust framework for developing HTTP-enabled service APIs that expose services and data. It may be accessed by a wide range of clients, including browsers, mobile devices, desktop computers, and tablets. Because it is an HTTP service, it may reach many clients.

After understanding what C# Web API is, you will explore the need for Web API.

Why Do You Need C# Web API?

  • Web API allows access to service data from web browsers, mobile apps, and other devices.
  • Web API aids in the development of lightweight, maintainable web services.
  • Web API also supports JSON, XML, and other data formats.
  • Web API helps develop services that support caching, request/response headers, versioning, etc.

Features of C# Web API

What is API in ASP.NET c#?

There are five features of C# Web API, they are:

  1. Routing: It helps in routing through different APIs.
  2. Controller: It gives functional capabilities to the web application.
  3. Model: It gives the structural capabilities to the web application.
  4. Filter: It gives filters to the web application. 
  5. Action Result: It can keep the action logos user, such as data retrieval.

These are the features of C# Web API. Now, try to implement these features with the help of a project.

New Course: Full Stack Development for Beginners

Learn Git Command, Angular, NodeJS, Maven & MoreEnroll Now

What is API in ASP.NET c#?

Implementation of C# Web API

What is API in ASP.NET c#?

1. You will create an asp.net core web API project named EmpAPI1 in the visual studio.

What is API in ASP.NET c#?

2. Then, you will install a NuGet Package called Microsoft.EntityFrameworkCore.Sqlite Package. You will use this to interact with the sqlite database using Web API.

What is API in ASP.NET c#?

3. First, you must create a “Models” folder to store the schema for the project.

What is API in ASP.NET c#?

4. Then you must create a class file named Employee.cs in this folder. You will define various properties in this class.

Code:

using Microsoft.EntityFrameworkCore;

using System;

using System.Collections.Generic;

using System.ComponentModel.DataAnnotations;

using System.Linq;

using System.Threading.Tasks;

namespace empapi1.Models

{

    public class Employee

    {

  [Key]

        public int EmpId { get; set; } 

   //Unique Identifier

        public string Name { get; set; } 

   //Name of the employee

        public string Dept { get; set; }

   //Name of the employee

        public string Address { get; set; }

   //Name of the employee

    }

}

What is API in ASP.NET c#?

5. Now the entity framework core also requires a context object class. Context objects allow querying and saving of data. So you must make another class in the Models folder named EmployeeContext.cs 

Code:

using Microsoft.EntityFrameworkCore;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading.Tasks;

namespace empapi1.Models

{

    public class EmployeeContext : DbContext

    {

//this object is configuration of the context.

        public EmployeeContext(DbContextOptions<EmployeeContext> options)

            : base(options)

        {

            Database.EnsureCreated();

// To ensure that database is created through dbcontext

        }

        public DbSet<Employee> employees { get; set; }

    }

}

6. Now you will update the ConfigureServices in startup.cs file with the AddDbContext entry.

services.AddDbContext<EmployeeContext>(o => o.UseSqlite("Data source=employees.db"));

With this, Entity framework is done. Now, you will make a repository. A repository is an abstraction layer between our application and data access layer which is in this case the “EmployeeContext”. 

What is API in ASP.NET c#?

Full Stack Web Developer Course

To become an expert in MEAN StackView Course

What is API in ASP.NET c#?

7. Now, you will create a folder named “Repositories”. Then you must create an interface called “IEmpRepository.cs”. This interface will represent the operations that will be performed on the database.

Code:

using empapi1.Models;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading.Tasks;

namespace empapi1.Repositories

{

    public interface IEmpRepository

    {

//This will retrieve all Employee entries

        Task<IEnumerable<Employee>> Get();

//This will retrieve a particular Employee entry.

        Task<Employee> Get(int EmpId);

//This will create an Employee entry

        Task<Employee> Create(Employee employee);

//This will update an Employee entry

        Task Update(Employee employee);

//This will delete an Employee entry

        Task Delete(int EmpId);

    }

}

What is API in ASP.NET c#?

8. Now, you will create a class EmployeeRepository to add implementation to the above operations.

Code:

using empapi1.Models;

using Microsoft.EntityFrameworkCore;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading.Tasks;

namespace empapi1.Repositories

{

    public class EmployeeRepository : IEmpRepository

    {

        private readonly EmployeeContext _context;

        public EmployeeRepository(EmployeeContext context)

        {

            _context = context;

        }

      public async Task<Employee> Create(Employee employee)

        {

//we are using Add method of dbset to insert entry

            _context.employees.Add(employee);

            await _context.SaveChangesAsync();

            return employee;

        }

      public async Task Delete(int EmpId)

        {

//we are using findasync method of dbset to find entry

            var employeeToDelete = await _context.employees.FindAsync(EmpId);

//we are using Remove method of dbset to delete entry

            _context.employees.Remove(employeeToDelete);

            await _context.SaveChangesAsync();

        }

      public async Task<IEnumerable<Employee>> Get()

        {

//we are using ToListAsync method of dbset to show all entry

            return await _context.employees.ToListAsync();

        }

      public async Task<Employee> Get(int EmpId)

        {

//we are using findasync method of dbset to find specific entry

            return await _context.employees.FindAsync(EmpId);

        }

      public async Task Update(Employee employee)

        {

            _context.Entry(employee).State = EntityState.Modified;

            await _context.SaveChangesAsync();

        }

    }

}

Free Course: Programming Fundamentals

Learn the Basics of ProgrammingEnroll Now

What is API in ASP.NET c#?

9. Now you must update the ConfigureServices in the startup.cs file with the AddScoped entry. Addscoped will register an instance of EmployeeRepository.

services.AddScoped<IEmpRepository, EmployeeRepository>();

And with this, the R=repositories are finished. Now you must create a web API controller. An API controller is a class that is responsible for handling requests at endpoints.

What is API in ASP.NET c#?

10. Now, add a web API controller in Controller. It will be an empty API controller. It will be named “EmployeesController.cs”.

Code:

using empapi1.Models;

using empapi1.Repositories;

using Microsoft.AspNetCore.Http;

using Microsoft.AspNetCore.Mvc;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading.Tasks;

namespace empapi1.Controllers

{

    [Route("api/[controller]")]

   [ApiController]

    public class EmployeesController : ControllerBase

    {

        private readonly IEmpRepository _empRepository;

        public EmployeesController(IEmpRepository empRepository)

        {

            _empRepository = empRepository;

        }

//HttpGet signifies that this method will handle all Get 

//Http Request

        [HttpGet]

        public async Task<IEnumerable<Employee>> GetEmployees()

        {

            return await _empRepository.Get();

        }

        [HttpGet("{EmpId}")]

        public async Task<ActionResult<Employee>> GetEmployees(int EmpId)

        {

            return await _empRepository.Get(EmpId);

        }

//HttpPost signifies that this method will handle all Post 

//Http Request

        [HttpPost]

        public async Task<ActionResult<Employee>> PostEmployees([FromBody] Employee employee)

        {

        var newEmployee = await _empRepository.Create(employee);

            return CreatedAtAction(nameof(GetEmployees), new { EmpId = newEmployee.EmpId }, newEmployee);

        }

//HttpPut signifies that this method will handle all Put 

//Http Request

        [HttpPut]

        public async Task<ActionResult> PutEmployees(int EmpId, [FromBody] Employee employee)

        {

//Check if the given id is present database or not

// if not then we will return bad request

            if (EmpId != employee.EmpId)

            {

                return BadRequest();

            }

            await _empRepository.Update(employee);

            return NoContent();

        }

//HttpDelete signifies that this method will handle all 

//Http Delete Request

        [HttpDelete("{EmpId}")]

        public async Task<ActionResult> Delete(int EmpId)

        {

         var employeeToDelete = await _empRepository.Get(EmpId);

// first we will check i the given id is 

//present in database or not

            if (employeeToDelete == null)

                return NotFound();

            await _empRepository.Delete(employeeToDelete.EmpId);

            return NoContent();

        }

    }

}

Full Stack Java Developer Course

In Partnership with HIRIST and HackerEarthEXPLORE COURSE

What is API in ASP.NET c#?

Now execute it

What is API in ASP.NET c#?

First, try the Get method. This shows the current database.

What is API in ASP.NET c#?

As you can see this shows an empty database.

Now, try the Post method to create an entry.

What is API in ASP.NET c#?

Now, try to execute the Get method again.

What is API in ASP.NET c#?

As you can see, it created one employee entry. 

Now try to change some values in the same entry using the Put method. 

What is API in ASP.NET c#?

Now, try the get operation again. And here it got updated.

What is API in ASP.NET c#?

Now try the Delete Method to delete an entry. 

What is API in ASP.NET c#?

Now, use the Get method again. 

What is API in ASP.NET c#?

And as you can see, that entry got deleted. 

And this is all for the C# Web API tutorial. Now, this tutorial will discuss the potential steps you could take to move forward.

Advance your career as a MEAN stack developer with the Full Stack Web Developer - MEAN Stack Master's Program. Enroll now!

Next Steps

"C# Rest API" can be your next concept to learn. REST is an abbreviation for Representational State Transfer. REST is a distributed system of architectural style and is premised on a set of concepts that defines and addresses network resources.

Simplilearn's  Post Graduate Program in Full-Stack Development course will be ideal if you want a more comprehensive study that goes beyond Mobile and Software Development. This online coding Bootcamp, by Caltech CTME, covers the most in-demand programming languages and skills required for success in software development today. It's time to go exploring.

Do you have any questions about this C# Web API tutorial? Please add them in the comments section at the base of this page if you do. Our experts will be glad to reply to your questions as soon as possible!

About the Author

What is API in ASP.NET c#?
Kartik Menon

Kartik is an experienced content strategist and an accomplished technology marketing specialist passionate about designing engaging user experiences with integrated marketing and communication solutions.

What are the 3 types of APIs?

Web APIs.
Open APIs. Open APIs, also known as external or public APIs, are available to developers and other users with minimal restrictions. ... .
Internal APIs. In contrast to open APIs, internal APIs are designed to be hidden from external users. ... .
Partner APIs. ... .
Composite APIs. ... .
REST. ... .
JSON-RPC and XML-RPC. ... .

How to use API in asp net?

Although ASP.NET Web API is packaged with ASP.NET MVC, it is easy to add Web API to a traditional ASP.NET Web Forms application. To use Web API in a Web Forms application, there are two main steps: Add a Web API controller that derives from the ApiController class. Add a route table to the Application_Start method.

How to create an API in asp net c#?

This will open New Project popup as below..
Create Web API project. In the New Project popup, expand Visual C# and select Web node in the left pane. ... .
Select Web API Template. Select Web API in the above popup. ... .
Web API project. ... .
Web API project. ... .
Create Web API Project. ... .
Select Project Template. ... .
Open NuGet. ... .
Install Web API Package..

What is REST API C#?

In simple terms a REST API allows applications to interact with each other and exchange data. For example, let's say you are building a mobile application or a web application. In that application you want to display weather data like temperature, humidity, wind speed etc.