How to Build a REST API in .Net Core with C#

How to Create REST API in .Net Using C# and Visual Studio

In this tutorial and subsequent ones, you will learn how to create a .NET REST API in C# using Visual Studio. In this first part, we would create a REST API that returns a list of friends.

Next we would add the endpoints for INSERT, UPDATE and DELETE.

Finally, we would generate the UI (Razor) pages using Visual Studio very easily.

  1. Setup the Project
  2. Create the Model and Controller
  3. Making a GET Request
  4. Making a POST Request
  5. PUT Request
  6. Delete Request
  7. Next Steps

 

1. Setup the Project and Create the Model

Start a new project in Visual Studio

In the Project template window, choose ASP.Net Core Web Application as shown below:

Choose ASP.Net Core Web Application
Choose ASP.Net Core Web Application

 

Give the project a name. I call it APITutorial.

Click on Ok.

In the next window, choose API as shown below:

Choose API
Choose API

 

Click on OK

Now, the project sets up. Then open the ValuesController.cs file which is inside the Controllers folder.  You will see that a basic REST controller is set up with placeholders for GET, POST, PUT and DELETE.

If you run the applications, you can visit the route https://localhost:44385/api/values. It returns a response:  [“value1”, “value2”]

So we now want to write the function that returns a list of friend.

 

2. Create the Model and Controller

First create a class called Friend. This class would have four fields: firstname, lastname, location and dateOfHire.

This class is shown below:

    public class Friend
    {
        private string firstname { get; set; }
        private string lastname { get; set; }
        private string location { get; set; }
        private DateTime dateOfHire { get; set; }

        public Friend()
        {
        }

        public Friend(string firstname, string lastname, string location, DateTime dateOfHire)
        {
            this.firstname = firstname;
            this.lastname = lastname;
            this.location = location;
            this.dateOfHire = dateOfHire;
        }
    }

 

We then need to create the controller class inside the controllers folder.

Right-click on the controller folder and choose Add New Controller.

Choose API Controller in the Add Scaffold window as shown below:

Creating a REST API Controller
Creating a REST API Controller

Click on Add.

In the next window, give it a name FriendController

Then ok.

 

3. Making a GET Request

You’ll see that the controller file is generated with some content. Adjust the code in the get section to the following:

// GET: api/Friend
[HttpGet]
public List<Friend> Get()
{
    List<Friend> friends = new List<Friend>();
    friends.Add(new Friend("Kindson", "Munonye", "Budapest", DateTime.Today));
    friends.Add(new Friend("Oleander", "Yuba", "Nigeria", DateTime.Today));
    friends.Add(new Friend("Saffron", "Lawrence", "Lagos", DateTime.Today));
    friends.Add(new Friend("Jadon", "Munonye", "Asaba", DateTime.Today));
    friends.Add(new Friend("Solace", "Okeke", "Oko", DateTime.Today));

    return friends;
}

Now you can run the application and access /api/friend

In the case of findById, use the code below:

// GET: api/Friend/5
[HttpGet("{id}", Name = "Get")]
public Friend Get(int id)
{
    Friend friend = friends.Find(f => f.id == id);
    return friend;
}

 

4. Making a POST Request

To make POST request, we need to modify the POST section of the controller file.

Since we are not using database yet, we would simply add the received friend object to the list and return the new list. The code is given below:

// POST: api/Friend
[HttpPost]
public List<Friend> Post([FromBody] Friend friend)
{
    friends.Add(friend);
    return friends;
}

You can test is to see. You can use either Postman or Advanced Rest Client(ARC).

 

5. PUT Request

Here, we would receive a friend object from the body of the PUT request. We’ll also receive the id in the URL.  Then we’ll do the following:

  • find to find the specified item in the list
  • update the item using the data in the request body
  • return the new list

The code is given below:

// PUT: api/Friend/5
[HttpPut("{id}")]
public List<Friend> Put(int id, [FromBody] Friend friend)
{
    Friend friendToUpdate = friends.Find(f => f.id == id);
    int index = friends.IndexOf(friendToUpdate);

    friends[index].firstname = friend.firstname;
    friends[index].lastname = friend.lastname;
    friends[index].location = friend.location;
    friends[index].dateOfHire = friend.dateOfHire;

    return friends;
}

 

6. Delete Request

In this case you simply find the item with the specified id.

Delete it and then return the modified list. The code is given below:

// DELETE: api/ApiWithActions/5
[HttpDelete("{id}")]
public List<Friend> Delete(int id)
{
    Friend friend = friends.Find(f => f.id == id);
    friends.Remove(friend);
    return friends;
}

 

7. Next Steps – MVC and Razor

If you have successfully completed this tutorial, then thumbs up to you! However there’s yet much to be done.

Therefore we would cover the following in subsequent tutorials:

  • Connect to a MS SQL Database
  • Use Entity Framework
  • Save data to database
  • Create an view using Razor and HTML

Do check the video series for a hand-on step by step and more explanation here in my YouTube Channel. And do remember to subscribe!

Happy learning!

Admin bar avatar

kindsonthegenius

Kindson Munonye is currently completing his doctoral program in Software Engineering in Budapest University of Technology and Economics

View all posts by kindsonthegenius →

Leave a Reply

Your email address will not be published. Required fields are marked *