Intro to Web API — C#, .NET

Photo by Federico Beccari on Unsplash

The demand for modern applications is increasing. every modern application requires some sort of data repository that can provide consistent data and also the ability to read and write this data in your web application.

APIs are not only for web applications, APIs are the standard way to expose your data resources across different development platforms (Desktop, Web, Mobile, etc..).

Today, I will walk you through an introductory level on how to make a web API service using .NET Core API and Entity Framework Core.
Let’s Get Started!!

1-Picking our Project Template.

  • Open VS.
  • Pick “ASP.NET Core Web API

2-Exploring the application

  • Startup.cs
    In this class, we configure our services and dependencies, as well as we can also specify our URL endpoints for our API controller that we will create soon.
  • appsettings.json
    this where you can add app-related resources like (Database connection string, API keys, JSON objects, etc…)

3-Preparing the application

  • Delete the Default Controller
    if you have the default controller that is under the Controllers folder, delete that controller since we won't need it for our purposes.

As you can see in the picture below, I have created a data folder and inside of the folder, I have also added 2 sub-folders where our entities and repositories/contracts will live in.

Folder hierarchy

You can check the code under this GitHub link here.

  • Adding required packages

You can install the packages whether from the Nuget Package manager or through the Package manager console

  • Adding connection string in appsettings.json
    -in the JSON file you need to add the connection string to the database so we can establish the connection with our local database.
    Example:
"ConnectionStrings": {"DefaultConnection": "Server=(local); Database=Your-Db-Name; Trusted_Connection=True;MultipleActiveResultSets=true"}

4- Adding the API controller

You can add the controller with predefined basic actions (PUT, GET, POST, DELETE).
To do that, right-click on the controller folder then, click on Add option and click on Controller sub-option and pick API on the left side and choose “API Controller with read/write actions”. name the controller “ProductController

Once that is done, you can see that there are some annotations on the top level of the class “ROUTE[“API/[controller]”] and [ApiContrller]” the first is for telling that application; to get to this top-level endpoint your URL needs to be prefixed with API/controllerName. the second one is for adding more functionality and features to the controller for API-specific operations.

5-Configuring our dependencies

  • In Startup.cs
    As you can see in the picture below, I’m Injecting the IproductRepo Interface to Provide a ProductRepo instance when instantiating the interface (Dependency Injection)
    Also, we added the Database context to use SQL-server and grab the Connection string from the appsettings.json file that we have modified above. Finally, I'm specifying to add the controllers to perform the Endpoint operations as well as removing the circular relationships(removes nested properties ‘recursive class stack overflow error.’).

6-Refactoring the ProductController to meet our business needs.

namespace NET_Core_API.Controllers{[Route("api/[controller]")][ApiController]public class ProductController : ControllerBase{private readonly IProductRepo _productRepo;//Injecting our Repositorypublic ProductController(IProductRepo productRepo){_productRepo = productRepo;}[HttpGet]//Get all productspublic ActionResult Get(){try{var products = _productRepo.GetAll();return Ok(products);}catch (Exception){return StatusCode(StatusCodes.Status500InternalServerError,"Database failure");}}[HttpGet("{id}")]//Get a single productpublic ActionResult Get(int id){try{var product = _productRepo.Get(id);return Ok(product);}catch (Exception){return StatusCode(StatusCodes.Status500InternalServerError,"Database failure");}}[HttpPost]//Created a new Prodcutpublic ActionResult Post(Product product){try{var existing = _productRepo.Get(product.ID);if (existing != null)return BadRequest("Product in Use");_productRepo.Save(product);return Created($"api/Product/{product.ID}", product);}catch (Exception){return StatusCode(StatusCodes.Status500InternalServerError,"Database failure");}}// PUT api/<ProductController>/5[HttpPut("{id}")]//Update exisitng productpublic ActionResult Put(int id, Product product){try{_productRepo.Save(product);return Ok(product);}catch (Exception){return StatusCode(StatusCodes.Status500InternalServerError,"Database failure");}}// DELETE api/<ProductController>/5[HttpDelete("{id}")]//Deleting an exisiting productpublic ActionResult Delete(int id){try{var productFound = _productRepo.Get(id);if (productFound == null)return NotFound("couldn't find resource");var result = _productRepo.Delete(productFound);if (result > 0){return Ok();}else{return StatusCode(StatusCodes.Status500InternalServerError,"Database Failure");}}catch (Exception){return StatusCode(StatusCodes.Status500InternalServerError,"Database failure");}}}}

7-Testing our Endpoints

I will be using Postman to test the API endpoints, there are many other tools to test the API endpoints, for this tutorial I will be using Postman for that.

Testing POST
— JSON string

{"name": "Cargo Pants","description": "Nice Cargo Pants","categories": [{"id": 0,"productID": 0,"categoryID": 0,"category" :{"name":"Fashion"}},{"id": 0,"productID": 0,"categoryID": 0,"category":{"name":"Street"}}]}

Response

{"id": 2,"name": "Cargo Pants","description": "Nice Cargo Pants","categories": [{"productID": 2,"categoryID": 5,"category": {"id": 5,"name": "Fashion","products": []}},{"productID": 2,"categoryID": 6,"category": {"id": 6,"name": "Street","products": []}}]}
Photo by Karan Bhatia on Unsplash

This is a very brief introduction to Web API in .NET Core. I will be writing another blog for the best practices you can follow to build maintainable and loose coupled API services soon.

Hope you’ve enjoyed this piece of content.

Solution Repo

SEE YOU AT THE NEXT ONE!!!

--

--

--

Software developer | Programming and Blockchain enthusiast

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Using Reaper Automixer for Livestreaming

How to Install OpenCPN on Your AIS Raspberry Pi for Maritime Research

CS373 Spring 2022: Week 6

Our first microservice in GoLang using gin-gonic as Framework

5 Reasons MangoApps Is The Perfect SharePoint Alternative

How IT lost its glamour and how DevOps comes to Rescue!

SQL Hack: How to get first value based on a time column without JOIN or Window Function?

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ibrahim Jaber

Ibrahim Jaber

Software developer | Programming and Blockchain enthusiast

More from Medium

Quick tip — Local environment configuration for Asp.Net Core apps

Learning Aspnet core 👩‍🏫

Implementing Unit Of Work And Repository Pattern With Dependency Injection In .Net 5

.NET 6 implementing a custom configuration provider