Introduction
API Web Service API is the application programming interface either for the web servers or web browsers it is the website development concept usually used in API-based website architecture for creating Web Applications like microservices. In the Given Below article, I will discuss the complete procedure of creating of API Web Service using Asp.net Core 5 and then we will see the output of the API Based Web Service. After this Process, we will Test All the Endpoints of Webservice using Swagger for POST GET DELETE AND PUT Requests.
Create your first RESTful Web service in Asp.net Core Web API
Step 1
First, create the Asp.net Core Web API in Visual Studio.
Step 2
Add the new project in your solution like Asp.net Core class library for Business Access Layer and Data Access Layer.
After Adding the BAL (Business Access Layer) And DAL (Data Access Layer)
All the data in Data Access Layer and all the CRUD operations are in Data Access Layer for Business logic we have a Business Access layer in which we will do our All operations related to our business.
Data Access Layer
Given below picture is the structure of our project according to our Initial steps.
Step 3
First, Add the Model Person in the Data Access Layer
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.ComponentModel.DataAnnotations;
- using System.ComponentModel.DataAnnotations.Schema;
- namespace DAL.Model
- {
- [Table("Persons", Schema = "dbo")]
- public class Person
- {
- [Key]
- [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
- public int Id { get; set; }
-
- [Required]
- [Display(Name = "UserName")]
- public string UserName { get; set; }
-
- [Required]
- [Display(Name = "UserPassword")]
- public string UserPassword { get; set; }
- [Required]
- [Display(Name = "UserEmail")]
- public string UserEmail { get; set; }
-
- [Required]
- [Display(Name = "CreatedOn")]
- public DateTime CreatedOn { get; set; } = DateTime.Now;
-
- [Required]
- [Display(Name = "IsDeleted")]
- public bool IsDeleted { get; set; } = false;
-
- }
- }
Step 4
Add the Interface for all the operation you want to perform.
Code is Giver Below,
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Threading.Tasks;
-
- namespace DAL.Interface
- {
- public interface IRepository<T>
- {
- public Task<T> Create(T _object);
-
- public void Update(T _object);
-
- public IEnumerable<T> GetAll();
-
- public T GetById(int Id);
-
- public void Delete(T _object);
-
- }
- }
Step 5
Apply the repository pattern in your project add the class repository person
Code is Given Below,
- using DAL.Data;
- using DAL.Interface;
- using DAL.Model;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
-
- namespace DAL.Repository
- {
- public class RepositoryPerson : IRepository<Person>
- {
- ApplicationDbContext _dbContext;
- public RepositoryPerson(ApplicationDbContext applicationDbContext)
- {
- _dbContext = applicationDbContext;
- }
- public async Task<Person> Create(Person _object)
- {
- var obj = await _dbContext.Persons.AddAsync(_object);
- _dbContext.SaveChanges();
- return obj.Entity;
- }
-
- public void Delete(Person _object)
- {
- _dbContext.Remove(_object);
- _dbContext.SaveChanges();
- }
-
- public IEnumerable<Person> GetAll()
- {
- try
- {
- return _dbContext.Persons.Where(x => x.IsDeleted == false).ToList();
- }
- catch (Exception ee)
- {
- throw;
- }
- }
-
- public Person GetById(int Id)
- {
- return _dbContext.Persons.Where(x => x.IsDeleted == false && x.Id == Id).FirstOrDefault();
- }
-
- public void Update(Person _object)
- {
- _dbContext.Persons.Update(_object);
- _dbContext.SaveChanges();
- }
- }
- }
Step 6
Add the Data Folder and then add the Db context class set the database connection using SQL Server before starting the migration check these four packages in All of your project.
Then add the project references in all of the Project Directory in API project and BAL Project
Like
Now Modify the start-up class in project solution.
Code of the start-up file is given below.
- using BAL.Service;
- using DAL.Data;
- using DAL.Interface;
- using DAL.Model;
- using DAL.Repository;
- using Microsoft.AspNetCore.Builder;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.AspNetCore.HttpsPolicy;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.EntityFrameworkCore;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.DependencyInjection;
- using Microsoft.Extensions.Hosting;
- using Microsoft.Extensions.Logging;
- using Microsoft.OpenApi.Models;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
-
- namespace AspNetCore5APIWebService
- {
- public class Startup
- {
- private readonly IConfiguration _configuration;
-
- public Startup(IConfiguration configuration)
- {
- _configuration = configuration;
- }
-
-
-
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(_configuration.GetConnectionString("DefaultConnection")));
- services.AddControllers();
- services.AddHttpClient();
- services.AddTransient<IRepository<Person>, RepositoryPerson>();
- services.AddTransient<PersonService, PersonService>();
- services.AddControllers();
- services.AddSwaggerGen(c =>
- {
- c.SwaggerDoc("v1", new OpenApiInfo { Title = "AspNetCore5WebApiService", Version = "v1" });
- });
- }
-
-
- public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
- {
- if (env.IsDevelopment())
- {
- app.UseDeveloperExceptionPage();
- app.UseSwagger();
- app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "AspNetCore5WebApiService v1"));
- }
-
- app.UseHttpsRedirection();
-
- app.UseRouting();
-
- app.UseAuthorization();
-
- app.UseEndpoints(endpoints =>
- {
- endpoints.MapControllers();
- });
- }
- }
- }
Then Add the DB Set Property in your Application Db Context Class
Code of Db Context Class is Given Below,
- using System;
- using System.Collections.Generic;
- using System.Text;
- using DAL.Model;
- using Microsoft.EntityFrameworkCore;
- using Microsoft.Extensions.Configuration;
- namespace DAL.Data
- {
- public class ApplicationDbContext : DbContext
- {
-
- public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
- {
-
- }
- protected override void OnModelCreating(ModelBuilder builder)
- {
- base.OnModelCreating(builder);
- }
- public DbSet<Person> Persons { get; set; }
- }
- }
Step 7
Now start the migration command for creating the table in database
After Executing the command, we have the migration folder in our Data Access Layer that contains the definition of person table.
Step 8
Add the Repository Person class then implement the interface and perform the suitable action according to the action defined in Interface.
Code of the file is Given Below,
- using DAL.Data;
- using DAL.Interface;
- using DAL.Model;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
-
- namespace DAL.Repository
- {
- public class RepositoryPerson : IRepository<Person>
- {
- ApplicationDbContext _dbContext;
- public RepositoryPerson(ApplicationDbContext applicationDbContext)
- {
- _dbContext = applicationDbContext;
- }
- public async Task<Person> Create(Person _object)
- {
- var obj = await _dbContext.Persons.AddAsync(_object);
- _dbContext.SaveChanges();
- return obj.Entity;
- }
-
- public void Delete(Person _object)
- {
- _dbContext.Remove(_object);
- _dbContext.SaveChanges();
- }
-
- public IEnumerable<Person> GetAll()
- {
- try
- {
- return _dbContext.Persons.Where(x => x.IsDeleted == false).ToList();
- }
- catch (Exception ee)
- {
- throw;
- }
- }
-
- public Person GetById(int Id)
- {
- return _dbContext.Persons.Where(x => x.IsDeleted == false && x.Id == Id).FirstOrDefault();
- }
-
- public void Update(Person _object)
- {
- _dbContext.Persons.Update(_object);
- _dbContext.SaveChanges();
- }
- }
Step 9 - Business Access Layer
Now perform the Business Logic first add the service folder in BAL layer then Add the service person class
Code of Service Person Class is given below
- using DAL.Interface;
- using DAL.Model;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
-
- namespace BAL.Service
- {
- public class PersonService
- {
- private readonly IRepository<Person> _person;
-
- public PersonService(IRepository<Person> perosn)
- {
- _person = perosn;
- }
-
- public IEnumerable<Person> GetPersonByUserId(string UserId)
- {
- return _person.GetAll().Where(x => x.UserEmail == UserId).ToList();
- }
-
- public IEnumerable<Person> GetAllPersons()
- {
- try
- {
- return _person.GetAll().ToList();
- }
- catch (Exception)
- {
- throw;
- }
- }
-
- public Person GetPersonByUserName(string UserName)
- {
- return _person.GetAll().Where(x => x.UserEmail == UserName).FirstOrDefault();
- }
-
- public async Task<Person> AddPerson(Person Person)
- {
- return await _person.Create(Person);
- }
-
- public bool DeletePerson(string UserEmail)
- {
-
- try
- {
- var DataList = _person.GetAll().Where(x => x.UserEmail == UserEmail).ToList();
- foreach (var item in DataList)
- {
- _person.Delete(item);
- }
- return true;
- }
- catch (Exception)
- {
- return true;
- }
-
- }
-
- public bool UpdatePerson(Person person)
- {
- try
- {
- var DataList = _person.GetAll().Where(x => x.IsDeleted!=true).ToList();
- foreach (var item in DataList)
- {
- _person.Update(item);
- }
- return true;
- }
- catch (Exception)
- {
- return true;
- }
- }
- }
- }
Step 10
Again, Modify the Start-Up Class for Adding Transient to register the service business Layer and Data Access Layers, classes
Code of the Start-up is given below.
- using BAL.Service;
- using DAL.Data;
- using DAL.Interface;
- using DAL.Model;
- using DAL.Repository;
- using Microsoft.AspNetCore.Builder;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.AspNetCore.HttpsPolicy;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.EntityFrameworkCore;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.DependencyInjection;
- using Microsoft.Extensions.Hosting;
- using Microsoft.Extensions.Logging;
- using Microsoft.OpenApi.Models;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
-
- namespace AspNetCore5APIWebService
- {
- public class Startup
- {
- private readonly IConfiguration _configuration;
-
- public Startup(IConfiguration configuration)
- {
- _configuration = configuration;
- }
-
-
-
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(_configuration.GetConnectionString("DefaultConnection")));
- services.AddControllers();
- services.AddHttpClient();
- services.AddTransient<IRepository<Person>, RepositoryPerson>();
- services.AddTransient<PersonService, PersonService>();
- services.AddControllers();
- services.AddSwaggerGen(c =>
- {
- c.SwaggerDoc("v1", new OpenApiInfo { Title = "AspNetCore5WebApiService", Version = "v1" });
- });
- }
-
-
- public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
- {
- if (env.IsDevelopment())
- {
- app.UseDeveloperExceptionPage();
- app.UseSwagger();
- app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "AspNetCore5WebApiService v1"));
- }
-
- app.UseHttpsRedirection();
-
- app.UseRouting();
-
- app.UseAuthorization();
-
- app.UseEndpoints(endpoints =>
- {
- endpoints.MapControllers();
- });
- }
- }
- }
Step 11
Add the Person Details API Controller for getting PUT POST AND DELETE endpoints
After adding the controller in the API project
Code of the Controller for Person Details is Given Below,
- using BAL.Service;
- using DAL.Interface;
- using DAL.Model;
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Extensions.Logging;
- using Newtonsoft.Json;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
-
- namespace AspNetCore5APIWebService.Controllers
- {
- [Route("api/[controller]")]
- [ApiController]
- public class PersonDetailsController : ControllerBase
- {
- private readonly PersonService _personService;
- private readonly IRepository<Person> _Person;
-
- public PersonDetailsController(IRepository<Person> Person, PersonService ProductService)
- {
- _personService = ProductService;
- _Person = Person;
-
- }
-
- [HttpPost("AddPerson")]
- public async Task<Object> AddPerson([FromBody] Person person)
- {
- try
- {
- await _personService.AddPerson(person);
- return true;
- }
- catch (Exception)
- {
-
- return false;
- }
- }
-
- [HttpDelete("DeletePerson")]
- public bool DeletePerson(string UserEmail)
- {
- try
- {
- _personService.DeletePerson(UserEmail);
- return true;
- }
- catch (Exception)
- {
- return false;
- }
- }
-
- [HttpPut("UpdatePerson")]
- public bool UpdatePerson(Person Object)
- {
- try
- {
- _personService.UpdatePerson(Object);
- return true;
- }
- catch (Exception)
- {
- return false;
- }
- }
-
- [HttpGet("GetAllPersonByName")]
- public Object GetAllPersonByName(string UserEmail)
- {
- var data = _personService.GetPersonByUserName(UserEmail);
- var json = JsonConvert.SerializeObject(data, Formatting.Indented,
- new JsonSerializerSettings()
- {
- ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
- }
- );
- return json;
- }
-
-
- [HttpGet("GetAllPersons")]
- public Object GetAllPersons()
- {
- var data = _personService.GetAllPersons();
- var json = JsonConvert.SerializeObject(data, Formatting.Indented,
- new JsonSerializerSettings()
- {
- ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
- }
- );
- return json;
- }
- }
- }
RESTful Web Service Results
Debug the project using visual studio Debugger
Swagger is already implemented in our project for documenting the web service in this project we have separate endpoints for getting POST DELETE AND PUT
For add the person we have add person endpoint that gives us the JSON object for sending the complete JSON object in the database.
POST Endpoint in Web API Service
If we want to Create the New Person in the database, we must send the JSON object to the endpoints then data is posted by swagger UI to POST endpoint in the controller then create person object creates the complete person object in the database.
DELETE Endpoint in Web API Service
For deletion of person, we have a separate endpoint delete employee from the database, we must send the JSON object to the end point then data is posted by swagger UI to call the endpoint DELETE person in the controller then person object will be deleted from the database.
GET All Endpoint in Web API Service
We have separate endpoints for all the operations like get all the person records from the Database by Hitting the GET endpoint that sends the request to the controller and in the controller, we have the separate End Point for Fetching all the records from the database.
GET End Point for Getting the Record by User Email
We have separate endpoints for all the operations like Get the record of the person by user email from the database by hitting the GET endpoint that sends the request to the controller and in the controller we have the separate endpoint for fetching the record based on user email from the database.
Delete End Point for Deleting the Record by User Email
We have separate endpoints for all the operations like delete the record of the person by user email from the database by hitting the DELETE endpoint that sends the request to the controller and in the controller we have a separate Endpoint for deleting the record based on User Email from the database.
Update End Point for Updating the Record by User Email
We have separate endpoints for all the operations like updating the record of the person by user email from the database by hitting the UPDATE endpoint that sends the request to the controller and in the controller, we have the separate End Point for Updating the record based on user email from the database.
Testing the RESTful Web Service
Step 1 - Run the Project
Run the project then in the browser swagger UI will be shown to the tester.
Step 2 - Test POST End Point
Now Click on Try Out Button then and then send the JSON Object to the AddPerson End Point that is already defined in our controller.
We have sent the JSON object to the endpoint of API as shown in the figure and the Response Body for this call is true means that our one object is created in the database.
Click the try out button to get the get all records
Step 4 - Test DELETE End Point
Now click on the try out button then and then send the JSON object to the Delete endpoint that is already defined in our controller.
We have sent the user email to the endpoints of API as shown in the figure and the response body for this call is true means that our one object is deleted in the database.
Step 5 - Test GET by User Email End Point
Now click on the try-out button then and then send the JSON object to the GET endpoint that is already defined in our controllers for getting a record based on person email.
We get the data from the database according to the user gmail Id
Project Resource Guideline
- First, download the given Project from my GitHub repository / from article resources.
- Open the project using visual studio
- Go to package manager console
- Add the migration
- Update the database
- Run the project
- Enjoy the beauty of web service API with swagger UI
“Happy API Development”
Conclusion
As a software engineer my opinion about RESTfull web services are a lightweight maintainable and scalable service that is built on the REST architecture. RESTfull architecture provides us the best way to develop cross platfroms application using the Asp.net Core Web API. I suggest all the online community that develop your Web application using RESTfull Web architecture and follow the best practices of coading for high efficieny of application.