Rasheed K Mozaffar
Posted on February 15, 2023
Application Programming Interfaces , or APIs for short , is a must know concept for software developers , as it's a really compelling and important type of projects that you should have in your arsenal , in this article we'll tackle some of the crucial points of APIs and we'll see a Web API in action with some coding examples to further solidify your understanding of the concept.
This is going to be a long article , so buckle up , and let's go !
This article will cover the following key points:
1: API definition according to the internet
2: What does an API do
3: A real world analogy to an API
4: Web API depicted in a graph
5: Creating a Web API using .Net and C#
When tackling large concepts , I like to kick things off with a definition from the internet , because the definition is always the base for the topic , thus it facilitates understanding the concept , so let's take a look at a definition.
API definition according to the internet
An Application Programming Interface (API) is a set of tools and protocols designed to allow two software applications to communicate with each other. In simple terms, an API acts as an interface between two pieces of software, allowing them to exchange information and interact with each other. An API essentially allows applications to talk to each other, making it possible for developers to integrate existing software with their own applications or create new applications or services.
This definition is a decent overview of what an API is , what it does , and why's it helpful.
The definition included something about allowing two applications to communicate with each other , well , let's discuss that in the next point.
What does a Web API do ?
Let's use a much simpler definition before diving deeper in the theory , an API is basically an interface that provides a set of functions to the user while also keeping the underlying implementation of these functions hidden.
You'll comprehend this even further when we use an analogy to dissect everything that I said before , and what I'll be saying next.
An Api works as a mediator between 2 or more separate applications , it sits between them and allows for communication between the 2 , when an application wants to retrieve some data from a database for example , essentially it sends a request to the API , the API then takes the request , processes it , then talks to the database to retrieve the required data , and send it back to the requesting application , where the data is then displayed to the end user , to put it into perspective , we'll assume we have an online store website , when the products page is loaded , the site sends a request to the API asking for all the products available in the database , the API receives the request , then fetches the data from the database and send it in some format to the client side , the front end developer who designed the website should figure out some cool way to display the product details in an appealing manner for the end user who's shopping on that website.
The previous example discussed something using a Web API which is a form of API that's accessible over the internet through the HTTP Protocol.
All APIs provide a set of functionality wether it's over the internet or somewhat else , at its core , an API is intermediary between 2 or more applications , when an API request is sent , it's primarily asking the API to either perform some action or retrieve some data.
A real world analogy to an API
Ok that was a lot of cryptic things if you are still new to this , and believe me I was there at first , it took me so long to understand half of what that even meant , so let's use an analogy from our real world that will help us illustrate the concept.
A Car Dashboard
When you get inside a car , you're presented with a dashboard that has loads of buttons , these buttons are the UI , and by clicking a button let's say the start engine button , the car will expectingly , turn on , but you haven't seen what happened when the car was turning on , the wiring and mechanism that makes the car start/stop , was hidden , and you were left with merely a start/stop button , well , if you take a look back at the simple definition , the API is again , an interface that provides a set of functions while keeping the underlying mechanism hidden , similarly in the car , the buttons provide actions , but how they perform these actions is happening behind the scene.
Bear with me here , the Car API , this's what I'll be calling it here , just for demonstration purposes, is providing you with the functions , by clicking a button , you're requesting the car API to do something , maybe turn the head lights on , or switch the volume up , change the air conditioner temp and so on.
Next stop , we'll be looking at a simple graph so we can then explain Web API more , let's move to the next point
Web API depicted in a graph
The client starts by sending a request through the internet , the internet then routes the request depending on the host , then the server receives the request , the server is where the actions or endpoints reside , these endpoints can perform some actions like fetching data from a data store , adding data to that data store , or delete existing data , once the request is processed and finished , the response gets sent back to the client.
An example could be you opening your web browser (The client in this case) and requesting www.google.com , by typing this in the search bar , you're sending a request through the internet , the host is google , when the google server receives your request ,it'll generate a proper response and send it back to you , which in this case , is Google's home page.
These messages being transferred back and forth are using a transfer protocol known as HTTP or Hyper Text Transfer Protocol , the protocol is defined before sending the request , nowadays , most websites use HTTPS , S standing for secure which is a safer protocol than the standard HTTP , because all messages are encrypted upon sending and then decrypted when received, it's also highly advised to use HTTPS rather than the standard HTTP when building new web projects because that helps keeping your app users secure and protected against unwanted threats.
A request to a certain endpoint could be like this:
https://Example.com/api/v1/products
https: The transfer protocol to be used
Example.com: The host to which the request will be routed
/api/v1/products: This is the path part , once the server is reached , the path is then used to determine which action to perform , in our example case , this action will retrieve all the products we have in our database.
✅ CHECKPOINT REACHED ✅
That was a lot of theory back there to absorb , in our last point here , we'll be looking at how we can build Web APIs , for that purpose , I'll be using .Net & C# , because why not , we'll use the ASP DotNet platform to build our basic API.
ASP stands for Active Server Pages in case you didn't know.
In spite of the fact of me using .Net and C# , you're not confined to this option , other programming languages also offer frameworks for building Web APIs , so pick whichever one you like , and let's begin
Building a Web API with .Net & C#
Open a folder where you want to store your Web API project , and start a new terminal window , we'll use the .Net CLI to create our project , if you don't know what the CLI is , I have an article on it which I'll be linking at the bottom of the article , when your terminal opens , type this command
dotnet new webapi -n MyFirstWebApi -o ApiDemo
This command will create a new Web API project with the name MyFirstWebApi inside a new directory called ApiDemo
If you open the newly created project , you should something similar to this:
I'm using Visual Studio For Mac , some files are hidden , if you were to open this in Vs Code for example , you might see some files that don't appear in that screenshot , like appsettings.development.json which in my case is nested within the appsettings.json , and 2 other folders called bin and obj , also the project file which's a file with the extension .csproj , all of these files are hidden by default in the Visual Studio IDE,
If you expand the controllers folder , you should see a C# file called WeatherForecastController.cs , this file is created by default when using the webapi template , but what's a controller ?
A controller is a class that contain relative endpoints for example , endpoints for managing users , endpoints related to user management can perform actions like the following:
1: Getting all users from the database
2: Deleting an existing user using its ID
3: Adding a new user to the database
These are some actions that User Management Controller should contain , also , while naming controllers , the word controller should exist in the name , you've seen that when you looked at the Weather Forecast Controller , it was named WeatherForecastController.cs , now let's look at the content of that controller:
The code inside it is just for generating some weather forecast details which isn't what we're here for , in this file , there are key points we want to address , for starter , the Api Controller Attribute , the [ApiController]
line decorating the controller class , this is basically used to identity that this controller is an API controller and by doing so , this controller obtains features like API specific behavior and Automatic HTTP 400 Responses and other things which aren't in the scope of this article , but just remember to always add that attribute to your API controllers.
Then we have the Route Attribute , or [Route("api/[controller"])]
, by default , it was only [Route("[controller]")]
, I added the /api part myself , and that's what you should do by convention , but Microsoft forgot it here , if you scaffold a new API controller , you will see that the route does in fact contain that /api portion , this route is the path for when the request is received , the [controller] in the path will be trimmed off the name and you'll be left with the controller name only , like Weather Forecast Controller becomes Weather Forecast , enough theory , let's test this , you can run the project by doing a dotnet run
, the api will be started for you and you can copy the URL from the terminal , and paste it in a tool like Postman or Insomnia , these 2 are tools for sending requests to APIs , something like an API client , paste the URL in there , set the request type to GET , add the path to the URL , like this:
http://localhost:5213/api/weatherforecast
Pay attention to not add the word controller to the end of the path , and press send , you should get something like this:
You might ask something like why did we pick HTTP GET ?
Well , go back to the controller file , and look above the Get endpoint , you'll see this attribute
[HttpGet(Name = "GetWeatherForecast")]
This attributes specifies that this endpoint is a GET method , there are other attributes , like HttpPost , HttpDelete , HttpPatch etc...
What's Next ?
Well , we've covered really a lot of things in here , and I hope it all made sense , for those who are wondering what't next ? The answer is , I'll be writing more articles on Web APIs using .Net , in fact , the next article will be all about writing code , we'll create a basic API with some CRUD operations , which will also be explained later on in an upcoming article , till then , keep learning , ACTIVELY !
The link for the Dotnet CLI Article:
https://dev.to/rasheedmozaffar/the-dotnet-cli-commands-27ej
Posted on February 15, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.