How to Build a Minimal ASP.NET Core Web API from Scratch
Objectives:
- To develop Minimal ASP.NET Core Web API from Scratch
- To convert a console application into ASP.NET Core web application to provide deep understanding of ASP.NET Core internals.
- Create and run web server in the converted application.
- Add minimal APIs in the application.
- Test the Minimal APIs using Postman tool
Prerequisites:
- Basic understanding of C# and .NET.
- Installed .NET SDK (version 6 and later versions).
- Familiarity with REST APIs.
What is Minimal API
A Minimal API is a simplified approach to building web APIs in ASP.NET Core. It was introduced in .NET 6, which reduces boilerplate code and focuses on streamlined, minimal configurations. Unlike traditional ASP.NET Core Controller-based APIs, Minimal APIs do not require controllers, attributes, or explicit routing configurations. Instead, developers can define routes and handle requests directly in the Program.cs file using minimal syntax.
Overview of Development Steps
We have to follow a number of steps in sequence such as
- Create a console application
- Change its project file to get bare skeleton of ASP.NET Core
- Change Program.cs file to create server in ASP.NET Core application
- Look at different API methods available in the application
- Create Minimal APIs for Company entity to go in-depth
- Create dummy database (avoiding SQLServer to keep tutorial simple)
- Get list of all companies
- Get a company by Id
- Create a new company and add to the list of companies
- Delete a company from the list of companies
- Update a company
Step 1
Open Visual Studio and create a console application using .NET Core Console template. (or, Visual Studio Code can be used).
- Solution name: MinimalWebApi
- Project name: MinimalWebApi
- SDK version: 8.0, (you can use version 6 or later)
Now look at the different files and folders created in the application.
Look at Program.cs file code.
// See https://aka.ms/new-console-template for more information
Console.WriteLine("Hello, World!");
Now look at the folder structure of application. We get the following structure from application root folder. When you build the application in debug mode, binaries are created inside these folders.
└───MinimalWebApi
├───bin
│ └───Debug
│ └───net8.0
└───obj
└───Debug
└───net8.0
├───ref
└───refint
Now look at the files in application's root folder. The sln file is for solution. It contains details of different projects of the application. We get the following:
.gitattributes
.gitignore
MinimalWebApi
MinimalWebApi.sln
Next, look at the files and folders in project's root folder.
MinimalWebApi.csproj
bin
obj
Program.cs
Open the project file, MinimalWebApi.csproj in Visual Studio by clicking the project. Look at its content.
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
Modify the project file as done below. The Exe related tag is removed and Sdk value is updated.
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
Save the project file. Now, we get the following message at top of Visual Studio.
One or more projects have changes which cannot be automatically handled by the project system. Please save other changes, and reload those projects to prevent data loss. Reload projects
Click Reload projects button. Now look in Solution explorer in Visual Studio. There are more files and folders added after saving the project file.
In fact, console application is now converted into ASP.NET Core application. The framework required for ASP.NET Core is installed in the application. Look at the other changes in solution.
Here is the tree structure of the files and folders of the Solution explorer.
├───.github
│ └───workflows
└───MinimalWebApi
├───bin
│ └───Debug
│ └───net8.0
├───obj
│ └───Debug
│ └───net8.0
│ ├───ref
│ ├───refint
│ └───staticwebassets
└───Properties
Properties folder is created. Look at its launchSettings.json file. This file provides the URL at which the web application will be launched. It also specifies that when application will run then browser will be launch at the specified URL.
{
"profiles": {
"MinimalWebApi": {
"commandName": "Project",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "https://localhost:61120;http://localhost:61121"
}
}
}
Run the application. The application is build first and a Message box appears with following message.
"Unable to connect web server 'MinimalWebApi'. The web server is no longer running."
Click Ok button of Message Box to close it.
Next look at the console window which has opened on running the application. It writes:
Hello, World!
C:\Users\ajeet\source\repos\MinimalWebApi\MinimalWebApi\bin\Debug\net8.0\MinimalWebApi.exe (process 14308) exited with code 0 (0x0).
Press any key to close this window . . .
Till now there is no issue on running the application. Now,delete all code from Program.cs and save the file and run the application again. We get following error. Why? Because Main method is missing now. It means that even if ASP.NET Core, application starts running from Main method. Even Main method is the entry point of ASP.NET Core application
Error.
Severity Code Description Project File Line Suppression State
Error (active) CS5001 Program does not contain a static 'Main' method suitable for an entry point MinimalWebApi C:\Users\ajeet\source\repos\MinimalWebApi\MinimalWebApi\CSC 1
Step 2
When you run the application, it runs and console window is opened. No browser is launched. Why? Because there is no server created till now. Now to create a server, modify the Program.cs file:
var builder = WebApplication.CreateBuilder();
var app = builder.Build();
app.Run();
Save the Program.cs file and run the application again. The default browser opens at https://localhost:61120/. It means that now the application is running at the URL hosted in the server. But the browser throws an error message as given below. It implies that no HTML page is found to render it at the URL.
Message: This localhost page can’t be found. No webpage was found for the web address: https://localhost:61120/
HTTP ERROR 404
Close Browser.
What did you learn?
To get its answer, you will have to understand the code that was added to host and run the application in server.
The WebApplication.CreateBuilder();
returns WebApplicationBuilder
type builder object. This object has many methods to build the web application. It can be used to configure the application for hosting, logging, configuration sources etc.
The Build()
method returns the configured application. It implies that application has been configured for logging, hosting etc. The ASP.NET Core is modular and allows developers to add or remove the configuration components as per business requirements.
The Run()
method runs the finally configured application. What it means? It means that after the Build()
method we get configured application but after that we can add HTTP middleware pipeline in the application and finally run the application using Run()
method. We have not added any middleware in the application yet.
Look at the comments in the following code.
var builder = WebApplication.CreateBuilder(); // get WebApplicationBuilder
var app = builder.Build(); // get configured app
app.Run(); // run the finally configured app
Step 3
Now should we configure the web host etc. in our application?
Before that we create a minimal web api. How?
The answer is, you can use different minimal API methods such as Map()
to create Minimal API in the application. Look at the following code. It adds a minimal API and sends response to client browser (Hello World message is the response).
var builder = WebApplication.CreateBuilder();
var app = builder.Build();
app.Map("/", async context => await context.Response.WriteAsync("Hello World"));
app.Run(); // run the configured app
Save the Program.cs file and run the application again.
The application runs at https://localhost:61120/ and browser writes the response message: Hello World. Why? The answer is, Map()
method takes the path as first argument and request delegate as 2nd argument. The path implies the string appended after the domain or base URL. The base URL is https://localhost:61120.
What did you learn?
If you have still doubt, read the Step 3 again.
We have seen that API can send message to client. Now we see more APIs in this regard. Read the following section.
Step 4
How to render API response in plain text format?
Add some APIs in the program class using different Map extension methods.
var builder = WebApplication.CreateBuilder();
var app = builder.Build();
app.Map("/", async context => await context.Response.WriteAsync("Hello World"));
app.Map("/test", async context => await context.Response.WriteAsync("Test World"));
app.MapGet("/more", async context => await context.Response.WriteAsync("Test More"));
app.Run(); // run the configured app
Save Program.cs file and run the app again.
App runs at https://localhost:61120/ and browser writes the response message: Hello World and at https://localhost:61120/test browser writes the response message: Test World and at https://localhost:61120/more browser writes the response message: Test More
Step 5
How to render API response in HTML format?
In the following code, we use MapGet to process GET request received from the client. There are MapPost, MapDelete etc. for different HTTP requests. In the code, we create a local response object and the HttpContext object for response is set with some information. Note that HttpContext
object are available in request and response both cases. In case of response, server uses the HttpContext of response. But to read data from client, it uses HttpContext of request. To send HTML formatted data to client, the Response.ContentType is set to text/html
.
var builder = WebApplication.CreateBuilder();
var app = builder.Build();
app.MapGet("/", async handler =>
{
var resp = handler.Response;
resp.HttpContext.Response.ContentType = "text/html";
await resp.WriteAsync("<h1>Hello World</h1>");
});
app.Run(); // run the configured app
Step 6
How to render response in JSON format?
Can you use the same approach as you followed in previous plain text case? Try the following. Paste the following code in Program.cs file and run the application.
var builder = WebApplication.CreateBuilder();
var app = builder.Build();
app.MapGet("/", async handler =>
{
var resp = handler.Response;
resp.HttpContext.Response.ContentType = "application/json";
await resp.WriteAsync( new { Id = 1, name = "Amit Kumar" }.ToString());
});
app.Run(); // run the configured app
What did you observe after running the above code?
Step 7
You have used anonymous object in previous case. Now, create a class called Person and send its information as response. The Person class is as follows:
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
Send Response with an entity details
using MinimalWebApi;
var builder = WebApplication.CreateBuilder();
var app = builder.Build();
app.MapGet("/", async handler =>
{
var resp = handler.Response;
resp.HttpContext.Response.ContentType = "application/json";
await resp.WriteAsync(new Person(){ Id = 1, Name = "Amit Kumar" }.ToString());
});
app.Run(); // run the configured app
Save all files and run the app again. You can unexpected result in browser. The result is as follows:
MinimalWebApi.Person
Now, the question is what went wrong. The answer is, the WriteAsync()
method takes a string argument. So we have used ToString() method to convert the object into string. Therefore, the fully qulaified class name is returned as MinimalWebApi.Person. To overcome this issue, we override the ToString() method of Person class. This is done in following piece of code.
namespace MinimalWebApi;
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public override string ToString()
{
return $"person has id {this.Id} and name is {this.Id}.";
}
}
Save all files of application and run the app again. We get the expected result.
person has id 1 and name is 1.
Step 8
How to create full-fledged minimal APIs for an entity?
Let, we want to create minimal APIs for Company entity. The Company entity is as follows. Create this class in the project.
namespace MinimalWebApi;
public class Company
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string Country { get; set; }
}
We create APIs of Company entity in a static class called CompanyApis
with extension method called UseCompanyApis. Why? The answer is, an extension method of IEndpointRouteBuilder can be used in Program class. The details is given ahead.
namespace MinimalWebApi;
public static class CompanyApis
{
public static void UseCompanyApis(this IEndpointRouteBuilder app)
{
}
}
In Program.cs file, use the API extension method:
using MinimalWebApi;
var builder = WebApplication.CreateBuilder();
var app = builder.Build();
app.UseCompanyApis();
app.Run();
Now, you have to add company APIs in CompanyApis. e.g.
namespace MinimalWebApi;
public static class CompanyApis
{
public static void UseCompanyApis(this IEndpointRouteBuilder app)
{
app.MapGet("/api/companies", async handler =>
{
var response = handler.Response;
response.ContentType = "application/json";
await response.WriteAsync(
"companies"
);
});
}
}
Step 9
Create sample database for Minimal API
Now create a sample database called SampleData to return some dummy data of companies, not string "companies"(as done previously). The class has a field _company
initialized with a list of companies and a method GetCompanies()
to return the list.
namespace MinimalWebApi;
public class SampleData
{
List<Company> _companies = new List<Company>()
{
new Company()
{
Id = 1,
Name = "Primus Software Ltd.",
Address = "NOIDA, UP",
Country ="India"
},
new Company()
{
Id = 2,
Name = "Google India Software Ltd.",
Address = "Gurugram, Haryana",
Country ="India"
}
};
public List<Company> GetCompanies()
{
return _companies;
}
}
Step 10
Get companies list from sample database
Now replace await response.WriteAsync( "companies"); by the followong:
using System.Text.Json; // for serialization
namespace MinimalWebApi;
public static class CompanyApis
{
public static void UseCompanyApis(this IEndpointRouteBuilder app)
{
app.MapGet("/api/companies", async handler =>
{
var response = handler.Response;
response.ContentType = "application/json";
var companies = new SampleData().GetCompanies();
await response.WriteAsync(
JsonSerializer.Serialize(companies)
);
});
}
}
Run the application at https://localhost:61120/api/companies. We get the result:
[
{
"Id": 1,
"Name": "Primus Software Ltd.",
"Address": "NOIDA, UP",
"Country": "India"
},
{
"Id": 2,
"Name": "Google India Software Ltd.",
"Address": "Gurugram, Haryana",
"Country": "India"
}
]
We have created the API that returns all the companies and next, we will create the API to return a company details given is company Id. Look at the next section in this regard.
Step 11
Create Minimal API to get an entity details
Create another API, GetCompanyById
.
using System.Text.Json;
namespace MinimalWebApi;
public static class CompanyApis
{
public static void UseCompanyApis(this IEndpointRouteBuilder app)
{
app.MapGet("/api/companies", async handler =>
{
var response = handler.Response;
response.ContentType = "application/json";
var companies = new SampleData().GetCompanies();
await response.WriteAsync(
JsonSerializer.Serialize(companies)
);
});
app.MapGet("/api/companies/{id:int}", async (int id, HttpContext handler) =>
{
var response = handler.Response;
response.ContentType = "application/json";
var companies = new SampleData().GetCompanies();
var company = companies.Find(c => c.Id == id);
await response.WriteAsync(
JsonSerializer.Serialize(company));
});
}
}
Run app at https://localhost:61120/api/companies/1,
We get response:
{
"Id": 1,
"Name": "Primus Software Ltd.",
"Address": "NOIDA, UP",
"Country": "India"
}
Run app at https://localhost:61120/api/companies/2, We get
{
"Id": 2,
"Name": "Google India Software Ltd.",
"Address": "Gurugram, Haryana",
"Country": "India"
}
Run app at https://localhost:61120/api/companies/2, we get null. It means that the company is not in the database. To show a meaningful information to the end-user, we use the next section.
Step 12
Handling null response, create a class to handle it
Create NotFoundException class. When an object of NotFoundException is created we pass the desired message.
namespace MinimalWebApi;
public class NotFoundException : Exception
{
public NotFoundException(string? message) : base(message)
{
}
}
Modify the code to use NotFoundException. The following code has minute error which use realize after running and testing the API.
using System.Text.Json;
namespace MinimalWebApi;
public static class CompanyApis
{
public static void UseCompanyApis(this IEndpointRouteBuilder app)
{
app.MapGet("/api/companies", async handler =>
{
var response = handler.Response;
response.ContentType = "application/json";
var companies = new SampleData().GetCompanies();
if(companies is null)
{
response.StatusCode = StatusCodes.Status404NotFound;
new NotFoundException($"No company was found.");
}
await response.WriteAsync(
JsonSerializer.Serialize(companies)
);
});
app.MapGet("/api/companies/{id:int}", async (int id, HttpContext handler) =>
{
var response = handler.Response;
response.ContentType = "application/json";
var companies = new SampleData().GetCompanies();
var company = companies.Find(c => c.Id == id);
if (company is null)
{
new NotFoundException($"No company was found with Id:{id}");
}
await response.WriteAsync(
JsonSerializer.Serialize(company));
});
}
}
What did you observe after running the code?
Answer: look the following section.
Step 13
Role of throw statement
Although the code is creating an object NotFoundException, the exception is not throw, so code will not work. Check it. Now create an exception by using throw statements.
using System.Text.Json;
namespace MinimalWebApi;
public static class CompanyApis
{
public static void UseCompanyApis(this IEndpointRouteBuilder app)
{
app.MapGet("/api/companies", async handler =>
{
var response = handler.Response;
response.ContentType = "application/json";
var companies = new SampleData().GetCompanies();
if(companies is null)
{
response.StatusCode = StatusCodes.Status404NotFound;
throw new NotFoundException($"No company was found.");
}
await response.WriteAsync(
JsonSerializer.Serialize(companies)
);
});
app.MapGet("/api/companies/{id:int}", async (int id, HttpContext handler) =>
{
var response = handler.Response;
response.ContentType = "application/json";
var companies = new SampleData().GetCompanies();
var company = companies.Find(c => c.Id == id);
if (company is null)
{
throw new NotFoundException($"No company was found with Id:{id}");
}
await response.WriteAsync(
JsonSerializer.Serialize(company));
});
}
}
Step 14
Test API for not found entity
Run app at https://localhost:61120/api/companies/3.
Result is as follows:
An unhandled exception occurred while processing the request.
NotFoundException: No company was found with Id:3
POST API for creating entity
In SampleData, create method to create a new company.
public Company CreateCompany(Company company)
{
var companies = GetCompanies();
var companyFound = companies.Find(c => c.Id == company.Id);
if(companyFound is null)
{
companies.Add(company);
return company;
}
return null;
}
CompanyApis:
using Microsoft.AspNetCore.Http.HttpResults;
using System.Text.Json;
namespace MinimalWebApi;
public static class CompanyApis
{
public static void UseCompanyApis(this IEndpointRouteBuilder app)
{
app.MapGet("/api/companies", async handler =>
{
var response = handler.Response;
response.ContentType = "application/json";
var companies = new SampleData().GetCompanies();
if (companies is null)
{
response.StatusCode = StatusCodes.Status404NotFound;
throw new NotFoundException($"No company was found.");
}
await response.WriteAsync(
JsonSerializer.Serialize(companies)
);
});
app.MapGet("/api/companies/{id:int}", async (int id, HttpContext handler) =>
{
var response = handler.Response;
response.ContentType = "application/json";
var companies = new SampleData().GetCompanies();
var company = companies.Find(c => c.Id == id);
if (company is null)
{
throw new NotFoundException($"No company was found with Id:{id}");
}
await response.WriteAsync(
JsonSerializer.Serialize(company));
});
app.MapPost("api/companies", async (Company company, HttpContext handler) =>
{
var response = handler.Response;
response.ContentType = "application/json";
var result = new SampleData().CreateCompany(company);
if(result is null)
{
response.StatusCode = StatusCodes.Status400BadRequest;
throw new NotFoundException("Company already exists");
}
else
{
response.StatusCode = StatusCodes.Status201Created;
response.Headers["is-created-company"]= "yes";
// Sending a success message along with the created company data
var responseData = new
{
message = "Company created successfully",
company = company
};
await response.WriteAsync(JsonSerializer.Serialize(responseData));
}
});
}
}
Step 15
Use Postman to test for POST request
Run app and run postman. POST, https://localhost:61120/api/companies Body: raw, JSON
Request body:
{
"Id": 3,
"Name": "Quark Software Ltd.",
"Address": "New Delhi",
"Country": "India"
}
Result:
{
"message": "Company created successfully",
"company": {
"Id": 3,
"Name": "Quark Software Ltd.",
"Address": "New Delhi",
"Country": "India"
}
}
GET, https://localhost:61120/api/companies
Result:
[
{
"Id": 1,
"Name": "Primus Software Ltd.",
"Address": "NOIDA, UP",
"Country": "India"
},
{
"Id": 2,
"Name": "Google India Software Ltd.",
"Address": "Gurugram, Haryana",
"Country": "India"
}
]
Step 16
Correcting the Issue of creating entity by using static methods in SampleData
The response does not include the added company. Modify the code. Convert non-static methods of SampleData into static methods and then change CompanyApis class for this change.
namespace MinimalWebApi;
public class SampleData
{
static List<Company> _companies = new List<Company>()
{
new Company()
{
Id = 1,
Name = "Primus Software Ltd.",
Address = "NOIDA, UP",
Country ="India"
},
new Company()
{
Id = 2,
Name = "Google India Software Ltd.",
Address = "Gurugram, Haryana",
Country ="India"
}
};
public static List<Company> GetCompanies()
{
return _companies;
}
public static Company CreateCompany(Company company)
{
var companies = GetCompanies();
var companyFound = companies.Find(c => c.Id == company.Id);
if(companyFound is null)
{
companies.Add(company);
return company;
}
return null;
}
}
APIs code for GET and POST
using Microsoft.AspNetCore.Http.HttpResults;
using System.Text.Json;
namespace MinimalWebApi;
public static class CompanyApis
{
public static void UseCompanyApis(this IEndpointRouteBuilder app)
{
app.MapGet("/api/companies", async handler =>
{
var response = handler.Response;
response.ContentType = "application/json";
var companies = SampleData.GetCompanies();
if (companies is null)
{
response.StatusCode = StatusCodes.Status404NotFound;
throw new NotFoundException($"No company was found.");
}
await response.WriteAsync(
JsonSerializer.Serialize(companies)
);
});
app.MapGet("/api/companies/{id:int}", async (int id, HttpContext handler) =>
{
var response = handler.Response;
response.ContentType = "application/json";
var companies = SampleData.GetCompanies();
var company = companies.Find(c => c.Id == id);
if (company is null)
{
throw new NotFoundException($"No company was found with Id:{id}");
}
await response.WriteAsync(
JsonSerializer.Serialize(company));
});
app.MapPost("api/companies", async (Company company, HttpContext handler) =>
{
var response = handler.Response;
response.ContentType = "application/json";
var result = SampleData.CreateCompany(company);
if(result is null)
{
response.StatusCode = StatusCodes.Status400BadRequest;
throw new NotFoundException("Company already exists");
}
else
{
response.StatusCode = StatusCodes.Status201Created;
response.Headers["is-created-company"]= "yes";
// Sending a success message along with the created company data
var responseData = new
{
message = "Company created successfully",
company = company
};
await response.WriteAsync(JsonSerializer.Serialize(responseData));
}
});
}
}
Run the app for POST, https://localhost:61120/api/companies again
{
"Id": 3,
"Name": "Quark Software Ltd.",
"Address": "New Delhi",
"Country": "India"
}
Result:
[
{
"Id": 1,
"Name": "Primus Software Ltd.",
"Address": "NOIDA, UP",
"Country": "India"
},
{
"Id": 2,
"Name": "Google India Software Ltd.",
"Address": "Gurugram, Haryana",
"Country": "India"
},
{
"Id": 3,
"Name": "Quark Software Ltd.",
"Address": "New Delhi",
"Country": "India"
}
]
Run app and run postman. POST, https://localhost:61120/api/companies
Body: raw, JSON Request body:
{
"Id": 3,
"Name": "Quark Software Ltd.",
"Address": "New Delhi",
"Country": "India"
}
Result:
{
"message": "Company created successfully",
"company": {
"Id": 3,
"Name": "Quark Software Ltd.",
"Address": "New Delhi",
"Country": "India"
}
}
GET, https://localhost:61120/api/companies
Result:
[
{
"Id": 1,
"Name": "Primus Software Ltd.",
"Address": "NOIDA, UP",
"Country": "India"
},
{
"Id": 2,
"Name": "Google India Software Ltd.",
"Address": "Gurugram, Haryana",
"Country": "India"
}
]
The response does not include the added company. Modify the code. Convert non-static methods of SampleData into static methods and then change CompanyApis class for this change.
namespace MinimalWebApi;
public class SampleData
{
static List<Company> _companies = new List<Company>()
{
new Company()
{
Id = 1,
Name = "Primus Software Ltd.",
Address = "NOIDA, UP",
Country ="India"
},
new Company()
{
Id = 2,
Name = "Google India Software Ltd.",
Address = "Gurugram, Haryana",
Country ="India"
}
};
public static List<Company> GetCompanies()
{
return _companies;
}
public static Company CreateCompany(Company company)
{
var companies = GetCompanies();
var companyFound = companies.Find(c => c.Id == company.Id);
if(companyFound is null)
{
companies.Add(company);
return company;
}
return null;
}
}
Complete code of CompanyApis static class
using Microsoft.AspNetCore.Http.HttpResults;
using System.Text.Json;
namespace MinimalWebApi;
public static class CompanyApis
{
public static void UseCompanyApis(this IEndpointRouteBuilder app)
{
app.MapGet("/api/companies", async handler =>
{
var response = handler.Response;
response.ContentType = "application/json";
var companies = SampleData.GetCompanies();
if (companies is null)
{
response.StatusCode = StatusCodes.Status404NotFound;
throw new NotFoundException($"No company was found.");
}
await response.WriteAsync(
JsonSerializer.Serialize(companies)
);
});
app.MapGet("/api/companies/{id:int}", async (int id, HttpContext handler) =>
{
var response = handler.Response;
response.ContentType = "application/json";
var companies = SampleData.GetCompanies();
var company = companies.Find(c => c.Id == id);
if (company is null)
{
throw new NotFoundException($"No company was found with Id:{id}");
}
await response.WriteAsync(
JsonSerializer.Serialize(company));
});
app.MapPost("api/companies", async (Company company, HttpContext handler) =>
{
var response = handler.Response;
response.ContentType = "application/json";
var result = SampleData.CreateCompany(company);
if(result is null)
{
response.StatusCode = StatusCodes.Status400BadRequest;
throw new NotFoundException("Company already exists");
}
else
{
response.StatusCode = StatusCodes.Status201Created;
response.Headers["is-created-company"]= "yes";
// Sending a success message along with the created company data
var responseData = new
{
message = "Company created successfully",
company = company
};
await response.WriteAsync(JsonSerializer.Serialize(responseData));
}
});
}
}
Run the app for POST, https://localhost:61120/api/companies again. pass the following data in request body.
Request body:
{
"Id": 3,
"Name": "Quark Software Ltd.",
"Address": "New Delhi",
"Country": "India"
}
Result:
[
{
"Id": 1,
"Name": "Primus Software Ltd.",
"Address": "NOIDA, UP",
"Country": "India"
},
{
"Id": 2,
"Name": "Google India Software Ltd.",
"Address": "Gurugram, Haryana",
"Country": "India"
},
{
"Id": 3,
"Name": "Quark Software Ltd.",
"Address": "New Delhi",
"Country": "India"
}
]
Step 16
Create DELETE API
Create another API for DeleteCompanyById(int id) in SampleData.
public static Company DeleteCompanyById(int id)
{
var companies = GetCompanies();
var companyFound = companies.Find(c => c.Id == id);
if (companyFound != null)
{
companies.Remove(companyFound);
return companyFound;
}
return null;
}
Use DeleteCompanyById
in API extension method
app.MapDelete("/api/companies/{id:int}", async (int id, HttpContext handler) =>
{
var response = handler.Response;
response.ContentType = "application/json";
var company = SampleData.DeleteCompanyById(id);
if (company is null)
{
response.StatusCode = StatusCodes.Status400BadRequest;
throw new NotFoundException($"No company was found with Id:{id} to delete.");
}
response.StatusCode = StatusCodes.Status200OK;
await response.WriteAsync(JsonSerializer.Serialize(company));
});
Run app at https://localhost:61120/api/companies
We get both companies.
Run DELETE, https://localhost:61120/api/companies/1 Then run GET, https://localhost:61120/api/companies
Result:
[
{
"Id": 2,
"Name": "Google India Software Ltd.",
"Address": "Gurugram, Haryana",
"Country": "India"
}
]
No comments:
Post a Comment