Skip to main content

WEB API in ASP.NET CORE MVC | EXPLAIN WEB API IN DEPTH by Shiva Sir

1️⃣ What is Web API?

🔹 Definition:

A Web API (Web Application Programming Interface) is a set of HTTP endpoints exposed by a server application that allows other applications (frontend, mobile, etc.) to communicate over the web.

In .NET Core, a Web API is a type of controller that returns data (usually JSON), not views (HTML).





2️⃣ Why Use Web API?

PurposeDescription
🔄 CommunicationEnables frontend and backend apps to communicate using HTTP
⚙️ ReusabilityBackend APIs can be used by web apps, mobile apps, desktop apps
🔐 Centralized Business LogicAll logic is managed on the server side
🚀 Lightweight & FastReturns raw data (JSON), which is faster than rendering views

3️⃣ Web API vs MVC

FeatureMVCWeb API
OutputReturns Views (HTML)Returns Data (JSON/XML)
Use CaseWeb applications (UI required)APIs for mobile, SPA, external systems
Controller TypeControllerApiController
Return TypeIActionResult with ViewActionResult<T> with data

4️⃣ Architecture of Web API in .NET Core

🧱 Layers in a Typical Web API Project:

  1. Model

    • Represents the data structure

    • Example: Student, Product, Employee

  2. Controller

    • Manages API endpoints

    • Handles HTTP requests (GET, POST, PUT, DELETE)

  3. DbContext (Data Access Layer)

    • Entity Framework Core class for database communication

  4. Database

    • SQL Server, PostgreSQL, etc.


🔄 Request Lifecycle:

  1. Client sends an HTTP request → https://api.site.com/products

  2. Router matches the endpoint → ProductController

  3. Action method is called → GetAllProducts()

  4. Data is fetched from the database via DbContext

  5. Data is returned as JSON using Ok(result)

  6. Client (e.g., React app or Postman) receives the JSON response


5️⃣ Key Attributes in Web API

AttributeDescription
[ApiController]Specifies the class is a Web API controller. Adds automatic model validation and behavior
[Route()]Defines the URL path to reach the action method
[HttpGet]Handles GET requests
[HttpPost]Handles POST (create) requests
[HttpPut]Handles PUT (update) requests
[HttpDelete]Handles DELETE requests

6️⃣ Return Types in Web API

Return TypeDescription
IActionResultBase type for any HTTP response
ActionResult<T>Strongly typed return data (like ActionResult<Student>)
Ok(data)Returns 200 OK with data
NotFound()Returns 404
BadRequest()Returns 400
CreatedAtAction()Returns 201 with location header

7️⃣ RESTful API Principles

Web APIs in .NET Core follow REST principles (REpresentational State Transfer):

MethodActionPurpose
GETReadGet data from server
POSTCreateSend new data to server
PUTUpdateModify existing data
DELETEDeleteRemove data

8️⃣ Entity Framework Core in Web API

  • EF Core is the ORM used to map C# objects to database tables.

  • Benefits:

    • Write LINQ instead of SQL

    • Manage migrations

    • Easy CRUD with DbSet<T>


9️⃣ Dependency Injection

  • Web API uses Dependency Injection (DI) to manage services like DbContext.

  • Automatically injects services into controllers.

csharp

public StudentController(AppDbContext context) { _context = context; }

🔒 10️⃣ Security in Web API (Basics)

MechanismPurpose
API KeyAuthenticate client requests
JWT (Token)Secure APIs using bearer tokens
HTTPSEncrypts data between client and server
CORSControls which frontend apps can access your API

1️⃣1️⃣ Middleware in Web API

  • Middlewares are used to process requests/responses.

  • Example: Authentication, Logging, Exception handling

In Program.cs:

csharp

app.UseAuthentication(); app.UseAuthorization(); app.UseCors();

1️⃣2️⃣ Versioning in Web API (Optional but Useful)

Helps manage changes over time:

csharp

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

[ApiVersion("1.0")] 

EXAMPLE OF API:

🔧 Step-by-Step Implementation:


✅ Step 2: Create Project

  1. Open Visual Studio

  2. Create a new project → ASP.NET Core Web API

  3. Name: StudentAPI

  4. Choose .NET 6/7 → Click Create


✅ Step 3: Create Student Model


public class Student { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } public string Course { get; set; } }

✅ Step 4: Create DbContext

Install EF Core packages:


Install-Package Microsoft.EntityFrameworkCore.SqlServer Install-Package Microsoft.EntityFrameworkCore.Tools

Now, create AppDbContext.cs:


public class AppDbContext : DbContext { public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { } public DbSet<Student> Students { get; set; } }

✅ Step 5: Configure Database Connection

In appsettings.json:


"ConnectionStrings": { "DefaultConnection": "Server=.;Database=StudentDB;Trusted_Connection=True;" }

In Program.cs:


builder.Services.AddDbContext<AppDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"))); builder.Services.AddControllers();

✅ Step 6: Create Student Controller

Controllers/StudentController.cs


[ApiController] [Route("api/[controller]")] public class StudentController : ControllerBase { private readonly AppDbContext _context; public StudentController(AppDbContext context) { _context = context; } // GET: api/student [HttpGet] public async Task<ActionResult<IEnumerable<Student>>> GetAll() { return await _context.Students.ToListAsync(); } // GET: api/student/1 [HttpGet("{id}")] public async Task<ActionResult<Student>> Get(int id) { var student = await _context.Students.FindAsync(id); if (student == null) return NotFound(); return student; } // POST: api/student [HttpPost] public async Task<ActionResult<Student>> Create(Student student) { _context.Students.Add(student); await _context.SaveChangesAsync(); return CreatedAtAction(nameof(Get), new { id = student.Id }, student); } // PUT: api/student/1 [HttpPut("{id}")] public async Task<IActionResult> Update(int id, Student student) { if (id != student.Id) return BadRequest(); _context.Entry(student).State = EntityState.Modified; await _context.SaveChangesAsync(); return NoContent(); } // DELETE: api/student/1 [HttpDelete("{id}")] public async Task<IActionResult> Delete(int id) { var student = await _context.Students.FindAsync(id); if (student == null) return NotFound(); _context.Students.Remove(student); await _context.SaveChangesAsync(); return NoContent(); } }

✅ Step 7: Run Migrations and Update DB


Add-Migration InitialCreate Update-Database

This creates the StudentDB database and Students table.


✅ Step 8: Test API Using Postman

Base URL: https://localhost:5001/api/student

OperationHTTP VerbURLBody (if needed)
Get All StudentsGET/api/student
Get by IDGET/api/student/1
CreatePOST/api/studentJSON: {"name":"Aman","age":21,"course":"C#"}
UpdatePUT/api/student/1JSON: updated values
DeleteDELETE/api/student/1

🏁 Final Structure:


StudentAPI/ │ ├── Controllers/ │ └── StudentController.cs │ ├── Models/ │ └── Student.cs │ ├── Data/ │ └── AppDbContext.cs │ ├── appsettings.json └── Program.cs

🧠 Is Web API REST or SOAP?

Short Answer:

A Web API can be either REST or SOAPit depends on how the API is designed.


🔍 Let’s Understand:

🔹 Web API

  • A general term for any API that can be accessed using the web (HTTP/HTTPS).

  • It is a technology-neutral term.

  • It could be implemented using REST, SOAP, GraphQL, gRPC, etc.


Common Types of Web APIs:

TypeDescription
REST APIMost common. Uses HTTP verbs (GET, POST, etc.), returns JSON or XML, stateless.
SOAP APIOlder, strict protocol. Uses XML, defined by WSDL, uses POST only.
GraphQL APIModern alternative to REST, client controls the data shape.
gRPC APIHigh-performance, binary-based, good for microservices.

📌 Example in .NET Core:

  • If you create a Web API using ASP.NET Core, it's by default a RESTful Web API.

    • Uses [ApiController], routes like /api/products, and returns JSON.

    • Uses HTTP methods like GET, POST, PUT, DELETE.

  • If you want to create a SOAP-based API, you would use WCF (Windows Communication Foundation) — not Web API.


✅ Summary Table:

AspectREST API (Web API)SOAP API (WCF)
FormatJSON (or XML)XML only
ProtocolHTTP/HTTPSHTTP, SMTP, TCP
FlexibilityLightweight, easy to consumeHeavy, strict standards
Common in .NETASP.NET Core Web APIWCF (Windows Communication Foundation)
ToolingWorks with Postman, browser, JSNeeds SOAP clients (WSDL)

Comments

Popular posts from this blog

Uncontrolled form input in React-JS

  Uncontrolled form input in React-JS? If we want to take input from users without any separate event handling then we can uncontrolled the data binding technique. The uncontrolled input is similar to the traditional HTML form inputs. The DOM itself handles the form data. Here, the HTML elements maintain their own state that will be updated when the input value changes. To write an uncontrolled component, you need to use a ref to get form values from the DOM. In other words, there is no need to write an event handler for every state update. You can use a ref to access the input field value of the form from the DOM. Example of Uncontrolled Form Input:- import React from "react" ; export class Info extends React . Component {     constructor ( props )     {         super ( props );         this . fun = this . fun . bind ( this ); //event method binding         this . input = React . createRef ();...

JSP Page design using Internal CSS

  JSP is used to design the user interface of an application, CSS is used to provide set of properties. Jsp provide proper page template to create user interface of dynamic web application. We can write CSS using three different ways 1)  inline CSS:-   we will write CSS tag under HTML elements <div style="width:200px; height:100px; background-color:green;"></div> 2)  Internal CSS:-  we will write CSS under <style> block. <style type="text/css"> #abc { width:200px;  height:100px;  background-color:green; } </style> <div id="abc"></div> 3) External CSS:-  we will write CSS to create a separate file and link it into HTML Web pages. create a separate file and named it style.css #abc { width:200px;  height:100px;  background-color:green; } go into Jsp page and link style.css <link href="style.css"  type="text/css" rel="stylesheet"   /> <div id="abc"> </div> Exam...

JDBC Database Connectivity using JSP and Servlet, Database connectivity on Java

JDBC Database Connectivity using JSP and Servlet, Database connectivity on Java JDBC:-   JDBC means Java database connectivity, it is used to connect from the front-end(application server) to the back-end(database server) in the case of Java web application. The database provides a set of tables to store records and JDBC will work similarly to the  bridge between the database table and application form. 1)  Class.forName("drivername")  // Manage Drive         Class.formName("com.mysql.jdbc.Driver");  // MYSQL      Class.forName ("oracle.jdbc.driver.OracleDriver"); //Oracle 2)  Manage Connection String     It establish connection from application server to database server, Java provide DriverManage class and getConnection that will return Connection object.    Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/databasename","username","password"); 3)  Manage Statement to...