One of the necessary skills for a modern developer is to create powerful web APIs. Microsoft makes this process easy with the use of Visual Studio 2022, so you can create scalable web APIs. In this guide you can learn the whole process of creating a web API with Visual Studio 2022, from the beginning to the end point which is testing it and using it.
Accessing suitable tools is important for both junior and expert developers. Expert ones usually use Visual Studio versions which have a license. Visual Studio 2022 also presents a community version which is free. This tutorial focuses on Visual Studio 2022 for creating web APIs, and it is not important which version you are using.
Prerequisites
Before starting to develop an API, make sure you have these prerequisites on your system:
-
Visual Studio 2022 must be installed on your system.
-
You need the NET 6.0 SDK or a newer version.
-
You need primary knowledge about C# programming.
-
You should also be familiar with HTTP concepts.
First step: Install Visual Studio 2022
If Visual Studio 2022 is not installed on your system, first you need to download it. You can download Visual Studio 2022 Professional / Enterprise from here for free with a valid license key. also to download other versions of Microsoft Visual Studio click here.
After downloading, run the installer and select “ASP.NET and web development” and make sure you have all the necessary factors for developing a web API project.
Second step: Creating a new Web API Project
When Visual Studio 2022 installation is completed and everything is OK, it is now time to create the first web API project. In order to create a project, first, run Visual Studio 2022, then do as follows:
-
Click on “Create a new project”.
-
Type “API” in the search box.
-
Select “ASP.NET Core Web API” from the theme list.
-
Click on “Next”.
-
Enter a name for your project, for example, “MyFirstWebAPI”.
-
Select a location for your project.
-
Click on “Create”.
In the next window, configuration options are visible. Take care below items are enabled.
-
“NET 6.0” must be selected as your target framework.
-
If you are just testing locally, deselect “Configuration for HTTPS”.
-
Enable “Use Controllers”. Notice that we are using a traditional method for this tutorial.
-
Click on “Create”.
Now Visual Studio creates a project theme with all the things you need to start a web API.
Third step: Understanding Project Structure
Before writing your code, let’s see what Visual Studio 2022 has created for us.
One of them is the “Controllers Folder”: this folder has API controllers that manage HTTP requests. Another one is the “program.cs” file, which is the starting point of the program. This is where services and middleware are configured. The next one is “appsettings.json”, which is a file for the configuration of your program settings. “weatherForecastController.cs” is a controller sample which is provided by the theme.
The theme has a practical API which returns weather forecast data. This will give you a good starting point to understand how web APIs work in ASP.NET.
Fourth step: Creating a Custom API Controller
In this step we can create our controller. To do this phase, follow the steps:
-
Right click on the Controllers folder.
-
Select Add > Controller.
-
Select “API Controller – Empty”.
-
Name it “ProductsController”.
These steps will create an empty controller. Then you should replace the generated code with the below.
using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; namespace MyFirstWebAPI.Controllers { [Route("api/[controller]")] [ApiController] public class ProductsController : ControllerBase { // For simplicity, we'll use a static list instead of a database private static List<Product> products = new List<Product> { new Product { Id = 1, Name = "Laptop", Price = 999.99m }, new Product { Id = 2, Name = "Smartphone", Price = 499.99m }, new Product { Id = 3, Name = "Headphones", Price = 149.99m } }; // GET: api/Products [HttpGet] public ActionResult<IEnumerable<Product>> GetProducts() { return products; } // GET: api/Products/1 [HttpGet("{id}")] public ActionResult<Product> GetProduct(int id) { var product = products.Find(p => p.Id == id); if (product == null) { return NotFound(); } return product; } // POST: api/Products [HttpPost] public ActionResult<Product> PostProduct(Product product) { // In a real app, validate the product product.Id = products.Count > 0 ? products.Max(p => p.Id) + 1 : 1; products.Add(product); return CreatedAtAction(nameof(GetProduct), new { id = product.Id }, product); } } public class Product { public int Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } } }
This controller will prepare CRUD basic operations for a simple product catalog.
Fifth Step: Run and Test API
Now it's time to see what your API does in reality. In order to run your code, press F5 or click the play button. Visual Studio 2022 will launch a browser window with a swagger interface. Swagger will provide you with a document and a testing interface for your API. Test GET, POST and other cases end points to see your API in practice. Also, you can use tools such as Postman or curl to test your API endpoints.
Step 6: Add Authentication
You can secure an end point for creating APIs. Visual Studio 2022 simplifies adding authentication. To do this:
-
Right click on your project in solution explorer.
-
Select “Add” > “New Scaffolded Item”.
-
Select “API Controller with actions, using Entity Framework”.
-
Then follow the wizard to create a secure controller.
At the end, update Program.cs in order to include authentication middleware:
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { // Configure JWT options here }); builder.Services.AddAuthorization(); // Make sure to add this before app.MapControllers() app.UseAuthentication(); app.UseAuthorization();
Seventh step: Web API Establishment
When your API becomes ready, Visual Studio 2022 will provide some establishment options. To do so, right-click on your project and select “Publish”. Select your target (Folder, IIS, Azure etc.). To configure your establishment, follow the wizard.
Advanced Features in Visual Studio 2022
Visual Studio 2022 includes multiple features that can improve your web API. Some of them are:
-
Entity Framework Core tools: they are for the first database approach or first code.
-
Docker integration: they are for containerization of your programs.
-
Operation profile: they are for optimizing your API operation.
-
Git integrated tools: they are for managing source control.
Conclusion
Creating a web API thanks to the rich tools that Microsoft provides, is very simple. This tutorial tries to teach you how to create, test and establish a basic web API with the use of the newest developing environment.
Visual Studio 2022 is still the preferred IDE of many developers for creating web APIs with .NET. It’s not important whether you are using a community, professional or enterprise version. Visual Studio 2022 will provide you with exceptional development experience in creating a strong and scalable web API.
Remember that staying up to date with developing tools and updating your knowledge, in the rapid world of development is very important. It's better to check and discover Visual Studio 2022 updates and new features which have been added to this software.
With try and test, you will create complicated APIs as soon as possible which can operate as your web and mobile program backbone.