Unit 6: SQL Server and ASP.NET Core Web API
I. Orientation: Data and Service Communication
This unit connects relational data management in Microsoft SQL Server with HTTP-based services built using ASP.NET Core Web API. SQL Server stores structured records reliably, while a Web API exposes application data and operations to clients such as browsers, mobile applications, and Postman (Microsoft's API testing tool).
- Defining principle: A database persists normalized data; an API provides controlled access to that data through request and response messages.
- Core convention: SQL works with tables, rows, columns, and relationships; REST works with resources, URLs, representations, and HTTP methods.
- Common data format: JSON is widely used for API bodies, for example
{ "id": 7, "name": "Asha" }. - Separation of concerns: Controllers handle HTTP concerns, services contain application logic, and data-access code communicates with SQL Server.
- Important assumption: Client input is untrusted and must be validated before it is stored or used.
II. Introduction to SQL Server: Relational Storage
SQL Server is a relational database management system (RDBMS) that stores related data in tables and processes requests through Transact-SQL (T-SQL). Its engine supports transactions, security, indexing, backup, and concurrent access.
A. Introduction to SQL Server
This topic establishes SQL Server as the persistent data layer for applications.
- Database structure: A database contains schemas, tables, views, stored procedures, functions, and other objects;
dbo.Studentsidentifies theStudentstable in thedboschema. - Relational model: Data is represented as rows and columns, with relationships established through keys rather than duplicated text.
- Transactions: A transaction groups operations so they satisfy atomicity, consistency, isolation, and durability (ACID); an account transfer either completes both updates or neither.
- Access mechanism: Applications commonly connect through a connection string containing the server, database, authentication mode, and encryption settings.
III. SQL Commands: Working with Data
SQL commands define database objects, retrieve records, change data, and control permissions. Their result is determined by the selected database, schema, predicates, and transaction context.
A. SQL Commands
SQL commands provide the executable language for creating and manipulating relational data.
- DDL, or Data Definition Language:
CREATE TABLE,ALTER TABLE, andDROP TABLEdefine or change structures. - DML, or Data Manipulation Language:
INSERT,UPDATE, andDELETEmodify rows;SELECTreads them. - DCL, or Data Control Language:
GRANT,DENY, andREVOKEmanage permissions for users and roles. - Transaction control:
BEGIN TRANSACTION,COMMIT, andROLLBACKcontrol a unit of work. - Worked example:
SQLSELECT Id, Name FROM dbo.Students WHERE Department = 'CSE' ORDER BY Name;
WHEREfilters rows, andORDER BYsorts the result without changing stored data.
IV. SQL Server Tables: Organized Records
A table is a named relational object whose columns describe attributes and whose rows represent individual records. Good table design makes valid data easy to store and retrieve.
A. SQL Server Tables
Tables define the physical and logical shape of application data.
- Column definition: Each column has a name and data type, such as
INT,NVARCHAR(100),DATE,DECIMAL(10,2), orBIT. - Nullability:
NULLmeans missing or unknown, not an empty string or zero;NOT NULLrequires a value. - Identity values:
IDENTITY(1,1)can generate integer keys beginning at 1 and increasing by 1. - Normalization: Separating
DepartmentsfromStudentsavoids repeating department details in every student row. - Performance: An index can accelerate searches such as
WHERE Email = ..., but indexes consume storage and slow writes.
V. Constraints: Enforcing Validity
Constraints are database rules that reject invalid states at the point of storage. They complement, but do not replace, validation in the API.
A. Constraints
Constraints express integrity requirements directly in SQL Server.
- Primary key:
PRIMARY KEY (Id)uniquely identifies each row and does not allowNULL. - Foreign key:
FOREIGN KEY (DepartmentId) REFERENCES Departments(Id)ensures that a referenced department exists. - Unique constraint:
UNIQUE (Email)prevents two rows from using the same email address. - Check constraint:
CHECK (Age >= 18)rejects values outside the stated condition. - Default constraint:
DEFAULT GETDATE()supplies a value when an insert omits the column. - Integrity effect: A foreign-key violation fails an insert or update instead of silently creating an orphaned record.
VI. Joins: Combining Related Data
A join combines rows from tables using a related condition, usually a primary-key and foreign-key pair. The join type determines which unmatched rows remain in the result.
A. Joins
Joins retrieve related information without physically merging tables.
- Inner join: Returns only matching rows:
SQLSELECT s.Name, d.Name AS DepartmentName FROM Students AS s INNER JOIN Departments AS d ON s.DepartmentId = d.Id; - Left join: Returns every row from the left table and
NULLfor missing right-side data; it can list all departments including those with no students. - Right and full joins: A right join preserves the right table; a full join preserves unmatched rows from both sides and is less common in routine API queries.
- Join condition:
ON s.DepartmentId = d.Iddefines matching; omitting it can produce a Cartesian product with unexpectedly many rows. - Efficiency: Indexing join columns and selecting only required columns reduces database work and response size.
VII. Introduction to REST Architecture: Resource-Oriented Services
REST (Representational State Transfer) is an architectural style in which clients manipulate representations of resources through a uniform interface. A student resource might be identified by /api/students/7.
A. Introduction to REST Architecture
REST organizes an API around resources rather than procedure names.
- Client-server separation: The client handles presentation, while the server manages data and rules.
- Statelessness: Each request contains the information needed to process it; the server does not depend on hidden client session state between requests.
- Uniform interface: Standard methods and resource URLs provide predictable operations.
- Representations: A stored student object may be represented as JSON, without exposing the database table directly.
- Cacheability and layering: Responses may be cached when permitted, and intermediaries such as gateways can sit between client and server.
VIII. HTTP Protocol and HTTP Methods: Request and Response Rules
HTTP (Hypertext Transfer Protocol) carries a request from a client to a server and a response back. A request includes a method, target URL, headers, and sometimes a body.
A. HTTP Protocol and HTTP Methods
HTTP methods communicate the intended operation on a resource.
- GET: Reads data and should not change server state;
GET /api/students/7requests one student. - POST: Creates a subordinate resource, commonly receiving JSON in the body and returning
201 Created. - PUT: Replaces a resource at a known URL and is generally idempotent, meaning repeating the same request has the same intended result.
- PATCH: Applies a partial modification, such as changing only
email. - DELETE: Removes a resource and commonly returns
204 No Contenton success. - Headers and body:
Content-Type: application/jsondescribes a JSON request body;Accept: application/jsonstates a preferred response format.
IX. HTTP Status Codes: Communicating Outcomes
An HTTP status code gives the client a standardized result category. Correct codes allow clients to distinguish success, invalid input, missing resources, and server failures.
A. HTTP Status Codes
Status codes are grouped by their first digit and should match the actual outcome.
- 2xx success:
200 OKreturns a representation,201 Createdconfirms creation, and204 No Contentconfirms success without a body. - 3xx redirection:
304 Not Modifiedcan support cache validation; it does not mean that an operation succeeded or failed in the usual API sense. - 4xx client error:
400 Bad Requestindicates malformed input,401 Unauthorizedindicates missing or invalid authentication,403 Forbiddenindicates insufficient permission, and404 Not Foundindicates no matching resource. - Conflict and validation:
409 Conflictsuits a duplicate or state conflict;422 Unprocessable Contentmay describe semantically invalid data where that convention is adopted. - 5xx server error:
500 Internal Server Errorindicates an unexpected server failure; detailed exception information should not be exposed in production.
X. Introduction to ASP.NET Core Web API: The Application Framework
ASP.NET Core Web API is a cross-platform framework for building HTTP services on .NET. It uses middleware, dependency injection, model binding, routing, filters, and serializers to turn requests into application responses.
A. Introduction to ASP.NET Core Web API
The framework supplies the pipeline in which API endpoints execute.
- Pipeline: A request passes through middleware such as exception handling, HTTPS redirection, routing, authentication, and authorization.
- Model binding: Route, query-string, and body values are converted into C# parameters or objects.
- Serialization: ASP.NET Core commonly serializes C# objects to JSON using
System.Text.Json. - Dependency injection: Services are registered and injected into controllers, reducing direct construction and improving testability.
XI. Building and Configuring Web APIs: From Project to Endpoint
Building a Web API means defining the project, registering framework services, configuring middleware, and mapping controllers. Configuration is normally centralized in Program.cs.
A. Building and Configuring Web APIs
Configuration determines which services and request-processing stages are available.
- Service registration:
CSHARPbuilder.Services.AddControllers(); builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); - Middleware order:
CSHARPapp.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers();
MapControllersexposes attribute-routed controller actions. - Configuration sources:
appsettings.json, environment variables, and user secrets can hold settings; passwords should not be committed to source control. - Environment behavior: Swagger and detailed diagnostics are commonly enabled in development, while production should use controlled logging and error responses.
XII. API Controllers: HTTP Entry Points
An API controller is a C# class that groups related endpoints and converts HTTP requests into application operations. It should remain focused on transport concerns.
A. API Controllers
Controllers receive bound input, invoke dependencies, and return action results.
- Base type: Inheriting from
ControllerBasesupplies API-oriented helpers such asOk,NotFound, andCreatedAtAction. - Controller marker:
[ApiController]enables automatic model validation responses and more consistent binding behavior. - Dependency injection: A constructor can receive
StudentServiceor a database context rather than creating it internally. - Action result:
ActionResult<T>permits either a typed success body or an error result, such asActionResult<StudentDto>. - Boundary responsibility: Controllers should translate an absent database record into
404, not return an unexplainednullwith200.
XIII. Routing Using Convention and Attribute Routing: Selecting Actions
Routing maps an HTTP method and URL to a controller action. It must produce stable, unambiguous resource addresses.
A. Routing using Convention and Attribute Routing
The two routing approaches differ in where URL patterns are declared.
- Convention routing: A conventional pattern such as
{controller}/{action}/{id?}derives routes from controller and action names; it is concise but less explicit for REST APIs. - Attribute routing: Attributes state the contract directly:
CSHARP[Route("api/[controller]")] [HttpGet("{id:int}")] public ActionResult<StudentDto> Get(int id) { ... } - Constraints:
{id:int}prevents a nonnumeric segment from selecting this action. - Route values versus query values:
/api/students/7uses a route value;/api/students?department=CSEuses a query value for filtering.
XIV. Data Transfer Objects (DTOs): Controlled API Shapes
A DTO is a purpose-specific object used to carry data across the API boundary. It prevents database entities from becoming an accidental public contract.
A. Data Transfer Objects (DTOs)
DTOs control exposed fields and separate input models from output models.
- Response DTO:
StudentDtomight exposeId,Name, andDepartmentNamewhile hiding an internal audit field. - Create DTO:
CreateStudentDtocan requireNameandDepartmentIdwithout accepting a client-suppliedId. - Update DTO:
UpdateStudentDtocan define exactly which fields a PUT operation replaces. - Validation:
[Required],[EmailAddress], and[StringLength(100)]provide declarative checks before service logic runs. - Mapping: Explicit mapping, such as
new StudentDto { Id = entity.Id, Name = entity.Name }, makes exposed data intentional.
XV. CRUD Operations Using Web API: The Resource Lifecycle
CRUD means Create, Read, Update, and Delete. A conventional student API maps each operation to an HTTP method and returns an appropriate status code.
A. CRUD Operations using Web API
CRUD endpoints implement the ordinary lifecycle of a resource.
- Create:
POST /api/studentsvalidates aCreateStudentDto, inserts a row, and returns201 Createdwith aLocationheader. - Read:
GET /api/studentsreturns a collection;GET /api/students/7returns one DTO or404. - Update:
PUT /api/students/7verifies existence, validates the replacement representation, and returns204or the updated representation. - Delete:
DELETE /api/students/7removes the row and returns204; deleting an absent resource commonly returns404. - Database safety: Parameterized queries or Entity Framework Core prevent SQL injection; transactions protect multi-step changes.
XVI. Swagger/OpenAPI Documentation: A Machine-Readable Contract
OpenAPI is a standard description of an HTTP API, and Swagger tools generate interactive documentation from that description. The document records paths, methods, parameters, schemas, and responses.
A. Swagger/OpenAPI Documentation
Swagger makes endpoint contracts visible and directly testable in a browser.
- Generated description:
AddSwaggerGendiscovers controller actions and produces an OpenAPI document. - Interactive UI: Swagger UI displays routes such as
GET /api/students/{id}and provides an “Execute” operation. - Schema value: DTO properties, required fields, and response types help consumers construct valid requests.
- Accuracy requirement: Documentation must reflect actual status codes, authentication requirements, and request bodies; a misleading schema is a maintenance defect.
XVII. Testing Web APIs using Postman: Verifying Behavior
Postman sends HTTP requests and displays status codes, headers, timing, and response bodies. It verifies the running API from the perspective of an external client.
A. Testing Web APIs using Postman
Postman testing checks both the happy path and defined failure behavior.
- Request setup: Select
POST, enterhttps://localhost:5001/api/students, choose raw JSON, and sendContent-Type: application/json. - Body example:
JSON{ "name": "Asha", "departmentId": 2 } - Assertions: Confirm
201for valid creation, aLocationheader, correct JSON fields, and persistence through a following GET. - Negative cases: Send a missing name, an unknown department ID, an invalid route such as
/api/students/abc, and a nonexistent ID to verify400,404, or validation behavior. - Environment variables: Variables such as
{{baseUrl}}and{{studentId}}keep requests reusable across development and testing environments. - Authentication check: When security is enabled, verify that missing, invalid, and authorized credentials produce the intended
401or403responses.
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →