The Ultimate Guide to a One-Stop Solution to C# Web API

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
Post Graduate Program: Full Stack Web Development

What Is C# Web API?

C#Web-API-What-img1

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

C#Web-API-feature-img1

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
New Course: Full Stack Development for Beginners

Implementation of C# Web API

Implementation-img1

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

Implementation-img2

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.

Implementation-img3

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

Implementation-img4.

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

    }

}

Implementation-img5.

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”. 

Implementation-img6.

Full Stack Web Developer Course

To become an expert in MEAN StackView Course
Full Stack Web Developer Course

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);

    }

}

Implementation-img7

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
Free Course: Programming Fundamentals

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.

Implementation-img8

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
Full Stack Java Developer Course

Now execute it

/Implementation-img9.

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

Implementation-img10.

As you can see this shows an empty database.

Now, try the Post method to create an entry.

Implementation-img11

Now, try to execute the Get method again.

Implementation-img12

As you can see, it created one employee entry. 

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

Implementation-img13

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

Implementation-img14.

Now try the Delete Method to delete an entry. 

Implementation-img15

Now, use the Get method again. 

Implementation-img16.

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

Kartik MenonKartik 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.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.