Introduction
In Day 6, we built our first controller-based .NET Core Web API using an Employee Management example. We created endpoints to retrieve, add, update, and delete employee records.
But have you ever wondered what happens when Angular, Postman, or another application calls an API?
For example, when a client sends a request to:
GET https://localhost:7001/api/employees/101How does the API understand the request? How does it return employee information? And why does the response usually contain JSON?
To understand API development properly, we need to understand the HTTP request-response cycle.
In this article, we will explore these concepts using practical examples in C# and .NET 8.
1. What Is an HTTP Request?
An HTTP request is a message sent by a client to a server to perform an operation or retrieve information.
A client can be:
An Angular or React application
Postman
A mobile application
Another backend service
A web browser
For example, suppose we want to retrieve employee information from our Employee Management API.
The client sends:
GET /api/employees/101 HTTP/1.1
Host: localhost:7001
Accept: application/jsonThis request contains several important parts.
Main components of an HTTP request
| Component | Description |
|---|---|
| HTTP Method | Defines the operation, such as GET or POST |
| URL | Identifies the resource |
| Headers | Provide additional information about the request |
| Body | Contains data sent to the server, when required |
A GET request normally does not need a request body. A POST request commonly sends data in its body.
2. Understanding HTTP Request Methods
HTTP methods describe the operation the client wants to perform.
Consider our Employee Management API:
| Method | Endpoint | Purpose |
|---|---|---|
| GET | /api/employees | Retrieve all employees |
| GET | /api/employees/101 | Retrieve one employee |
| POST | /api/employees | Create an employee |
| PUT | /api/employees/101 | Update an employee |
| DELETE | /api/employees/101 | Delete an employee |
For example, when a user submits an employee creation form, the frontend sends a POST request to the API.
The request body contains the employee information.
3. What Is JSON?
JSON stands for JavaScript Object Notation.
It is a lightweight data-interchange format used to exchange information between different applications.
JSON is language-independent and widely used in REST APIs.
Example:
{
"id": 101,
"name": "Rahul Sharma",
"department": "IT",
"email": "rahul@example.com"
}This JSON object represents an employee.
JSON supports the following data types:
| Data type | Example |
|---|---|
| String | "Rahul" |
| Number | 101 |
| Boolean | true |
| Array | [1, 2, 3] |
| Object | {"name": "Rahul"} |
| Null | null |
JSON is commonly used because it is readable, compact, and supported by most programming languages.
4. Understanding Request Headers
HTTP headers provide additional information about a request or response.
For example:
POST /api/employees HTTP/1.1
Host: localhost:7001
Content-Type: application/json
Accept: application/jsonLet's understand the important headers.
Content-Type
Content-Type tells the server which format is used in the request body.
For JSON:
Content-Type: application/jsonThis tells the API that the client is sending JSON data.
Accept
Accept tells the server which response format the client can handle.
For example:
Accept: application/jsonThis indicates that the client prefers a JSON response.
Authorization
The Authorization header is commonly used to send authentication credentials, such as a bearer token.
Authorization: Bearer YOUR_ACCESS_TOKENWe will explore authentication and JWT in later articles.
Important: Content-Type and Accept are not interchangeable. One describes the request representation; the other describes the response formats the client accepts.
5. What Is an HTTP Request Body?
The request body contains the data sent by the client to the API.
For example, when creating an employee, the client may send:
{
"name": "Amit Verma",
"department": "Finance",
"email": "amit@example.com"
}The API receives this data and processes it.
In .NET Core Web API, we can use a C# model to represent the incoming JSON data.
Employee model
namespace EmployeeManagementAPI.Models
{
public class Employee
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public string Department { get; set; } = string.Empty;
public string Email { get; set; } = string.Empty;
}
}Receiving JSON using [FromBody]
Inside our controller:
[HttpPost]
public IActionResult CreateEmployee([FromBody] Employee employee)
{
employee.Id = _nextId++;
Employees.Add(employee);
return CreatedAtAction(
nameof(GetEmployeeById),
new { id = employee.Id },
employee
);
}Here is what happens:
The client sends JSON in the request body.
ASP.NET Core reads the request body.
The JSON input formatter converts the JSON into an Employee C# object.
The controller receives that object as the
employeeparameter.The application processes the request.
The API returns an HTTP response.
This conversion from JSON into a C# object is called deserialization.
The [FromBody] attribute explicitly tells ASP.NET Core to bind the parameter from the request body. With [ApiController], complex types are generally inferred from the body, so explicitly adding [FromBody] is optional in this example.
6. What Is an HTTP Response?
After processing a request, the server sends an HTTP response back to the client.
An HTTP response generally contains:
Status code
Response headers
Response body (when applicable)
For example:
HTTP/1.1 200 OK
Content-Type: application/jsonResponse body:
{
"id": 101,
"name": "Rahul Sharma",
"department": "IT",
"email": "rahul@example.com"
}The status code tells the client whether the operation succeeded or failed.
The response body contains the requested information or details about the result.
7. Important HTTP Status Codes
HTTP status codes are grouped into five categories.
| Category | Meaning |
|---|---|
| 1xx | Informational |
| 2xx | Successful |
| 3xx | Redirection |
| 4xx | Client error |
| 5xx | Server error |
Some commonly used API status codes are:
| Status code | Meaning | Example |
|---|---|---|
| 200 | OK | Employee retrieved successfully |
| 201 | Created | Employee created successfully |
| 204 | No Content | Employee deleted successfully |
| 400 | Bad Request | Invalid request data |
| 401 | Unauthorized | Authentication required or invalid |
| 403 | Forbidden | User is not allowed to perform the operation |
| 404 | Not Found | Employee does not exist |
| 409 | Conflict | Request conflicts with current resource state |
| 500 | Internal Server Error | Unexpected server-side failure |
Returning status codes in C#
In a controller, we can return different HTTP responses using IActionResult.
[HttpGet("{id}")]
public IActionResult GetEmployeeById(int id)
{
var employee = Employees.FirstOrDefault(e => e.Id == id);
if (employee == null)
{
return NotFound();
}
return Ok(employee);
}Here:
Ok(employee)returns HTTP 200.NotFound()returns HTTP 404.
For creating a resource, we can return:
return CreatedAtAction(
nameof(GetEmployeeById),
new { id = employee.Id },
employee
);This returns HTTP 201 Created and provides a location for retrieving the newly created resource.
8. What Is Serialization in .NET Core Web API?
Serialization means converting a C# object into JSON or another data representation.
Suppose our API has this C# object:
var employee = new Employee
{
Id = 101,
Name = "Rahul Sharma",
Department = "IT",
Email = "rahul@example.com"
};When we return:
return Ok(employee);ASP.NET Core uses its configured output formatter to serialize the object into JSON for the HTTP response.
Conceptually, the result looks like:
{
"id": 101,
"name": "Rahul Sharma",
"department": "IT",
"email": "rahul@example.com"
}By default, modern ASP.NET Core Web API applications use System.Text.Json for JSON serialization and deserialization.
Manually serializing an object
We can also serialize an object in C# using System.Text.Json.
using System.Text.Json;
Employee employee = new Employee
{
Id = 101,
Name = "Rahul Sharma",
Department = "IT",
Email = "rahul@example.com"
};
string json = JsonSerializer.Serialize(employee);
Console.WriteLine(json);Output:
{"Id":101,"Name":"Rahul Sharma","Department":"IT","Email":"rahul@example.com"}The exact property-name formatting can depend on the serializer options used. ASP.NET Core's web defaults generally use camelCase for JSON property names.
9. What Is Deserialization in .NET Core?
Deserialization is the reverse process: converting JSON data into a C# object.
Example:
using System.Text.Json;
string json = """
{
"id": 101,
"name": "Rahul Sharma",
"department": "IT",
"email": "rahul@example.com"
}
""";
Employee? employee =
JsonSerializer.Deserialize<Employee>(json);
Console.WriteLine(employee?.Name);Output:
Rahul SharmaThe JSON data is converted into an Employee object, allowing us to work with strongly typed C# properties.
Remember:
Serialization: C# object → JSON
Deserialization: JSON → C# object
10. Practical Example: Complete Request and Response Flow
Let's connect the concepts using our Employee Management API.
Suppose a user wants to create a new employee from an Angular application or Postman.
Step 1: Client sends a POST request
Endpoint:
POST https://localhost:7001/api/employeesHeaders:
Content-Type: application/json
Accept: application/jsonRequest body:
{
"name": "Amit Verma",
"department": "Finance",
"email": "amit@example.com"
}Step 2: API receives the request
The controller receives the JSON data through model binding.
[HttpPost]
public IActionResult CreateEmployee([FromBody] Employee employee)
{
employee.Id = _nextId++;
Employees.Add(employee);
return CreatedAtAction(
nameof(GetEmployeeById),
new { id = employee.Id },
employee
);
}Step 3: API processes the request
The API assigns an ID and adds the employee to its in-memory collection.
Step 4: API sends the response
Status:
201 CreatedResponse body:
{
"id": 104,
"name": "Amit Verma",
"department": "Finance",
"email": "amit@example.com"
}Step 5: Client handles the response
The frontend receives the HTTP response and can display a success message or refresh the employee list.
This is the complete request-response cycle.
11. Understanding the Request-Response Lifecycle
Let's summarize what happens when a client communicates with our API.
Client creates an HTTP request.
The request travels to the API endpoint.
ASP.NET Core processes the incoming request through its middleware pipeline.
Routing selects the matching endpoint.
Model binding reads and converts incoming data.
The controller executes the required business operation.
The API creates an HTTP response.
The configured output formatter serializes the response object into JSON.
The client receives the response and processes it.
The simplified flow looks like this:
Angular / Postman
|
| HTTP Request
| JSON Body + Headers
v
.NET Core Web API
|
v
Middleware Pipeline
|
v
Routing and Model Binding
|
v
Controller / Action
|
v
Application Processing
|
v
HTTP Response
|
| Status Code + JSON
v
Angular / PostmanThis is a simplified view. Real applications can also include authentication, authorization, filters, services, database access, exception handling, and other middleware.
12. Common Mistakes While Working with JSON APIs
Here are some common issues developers encounter.
Mistake 1: Incorrect Content-Type
If the client sends JSON but specifies an incorrect Content-Type, the API may not process the request as expected.
Use:
Content-Type: application/jsonMistake 2: Sending invalid JSON
Incorrect JSON:
{
"name": "Amit",
"department": "Finance",
}The trailing comma makes this invalid JSON.
Correct JSON:
{
"name": "Amit",
"department": "Finance"
}Mistake 3: Confusing 401 and 403
401 means valid authentication has not been established.
403 means the request is not permitted, even though the caller may already be authenticated.
Mistake 4: Returning 200 for every operation
A successful API does not always need to return 200.
Choose meaningful status codes:
200 for a successful response with content.
201 for resource creation.
204 for successful operations without response content.
400 for invalid requests.
404 when a resource is not found.
Mistake 5: Assuming in-memory data is permanent
Our current Employee Management example uses a static in-memory collection.
The data is lost when the application restarts. Later in this series, we will connect our API to SQL Server using Entity Framework Core.
13. Interview Questions
Q1. What is JSON?
JSON is a lightweight, language-independent data format commonly used to exchange data between clients and APIs.
Q2. What is the difference between serialization and deserialization?
Serialization converts a C# object into JSON. Deserialization converts JSON into a C# object.
Q3. What is the difference between Content-Type and Accept?
Content-Type describes the format of the request or response body. Accept specifies the response formats the client can handle.
Q4. What is the purpose of the HTTP status code?
It communicates the result of an HTTP request, such as success, client error, redirection, or server error.
Q5. What is model binding in .NET Core Web API?
Model binding maps incoming HTTP request data, such as route values, query parameters, and request body data, to action method parameters or model properties.
Q6. Which JSON serializer is used by default in modern .NET Web APIs?
System.Text.Json is the default JSON serializer in modern ASP.NET Core Web API applications.
Q7. What is the difference between 200 and 201?
200 OK indicates that the request succeeded. 201 Created indicates that a resource was successfully created.
Conclusion
HTTP requests and responses are the foundation of Web API communication.
Whenever an Angular application, mobile app, or external service communicates with a .NET Core Web API, it uses HTTP to exchange information.
Understanding request methods, headers, JSON, status codes, serialization, and deserialization will help you build APIs that are easier to maintain and integrate with other applications.
We have now understood how data travels between a client and our Employee Management API.
In the next article, we will explore Dependency Injection (DI) in .NET Core Web API and understand how to manage services and dependencies without tightly coupling our application.
What's Next?
Day 8 – Dependency Injection in .NET Core Web API with Practical C# Examples.
Learn • Build • Grow Together
No comments:
Post a Comment