In this article I will create a simple ASP.NET Core Web API Application that allows me to list, add, and remove reminders. I will also build a quick Python Script that uses the Web API. In addition, I will show an example of ASP.NET Core Dependency Injection. If you haven't read my ASP.NET Core MVC from Scratch Tutorial and you are really new to this, I recommend reading that tutorial first. I spend a fair amount of time explaining the details, which my be really useful for you.

ASP.NET Core Web API

Rather than using Visual Studio, I've been writing all my ASP.NET Core tutorials and examples on my MacBook Pro running macOS and Visual Studio Code. I open up the bash terminal on macOS and create a new directory for my Web API application. I create the new application and restore the Nuget Packages using the .NET Core CLI, and open the application in Visual Studio Code.

mkdir RemindersSvc && cd $_

dotnet new
dotnet restore

code .

Now that I am in Visual Studio Code I have 3 housekeeping tasks: 1) add dependencies to project.json, 2) configure Kestrel as the server for the ASP.NET Core Web API Application, and 3) add a Startup Class as my entry point into the application.

I have 2 dependencies I need to add to project.json: Microsoft.AspNetCore.Server.Kestrel and Microsoft.AspNetCore.Mvc. Here is the new project.json for the ASP.NET Core Web API Application.

{
  "version": "1.0.0-*",
  "buildOptions": {
    "debugType": "portable",
    "emitEntryPoint": true,
    "preserveCompilationContext": true
  },
  "dependencies": {},
  "frameworks": {
    "netcoreapp1.0": {
      "dependencies": {
        "Microsoft.NETCore.App": {
          "type": "platform",
          "version": "1.0.0"
        },
        "Microsoft.AspNetCore.Server.Kestrel": "1.0.0",
        "Microsoft.AspNetCore.Mvc": "1.0.0"
      },
      "imports": "dnxcore50"
    }
  }
}

I run the dotnet restore command from the Command Palette in Visual Studio Code (CMD-SHIFT-P) to install these new dependencies.

I now configure Kestrel as the web server.

using System.IO;
using Microsoft.AspNetCore.Hosting;

namespace RemindersSvc {
    public class Program {
        public static void Main(string[] args) {
            var host = new WebHostBuilder()
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseStartup<Startup>()
                .Build();

            host.Run();
        }
    }
}

I also create the Startup Class as the entry point to the ASP.NET Core Web API Application. ASP.NET Core MVC is being added to the Dependency Injection Framework and ASP.NET Core middleware.

using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using RemindersSvc.Services;

namespace RemindersSvc {
    public class Startup {
        public void ConfigureServices(IServiceCollection services) {
            services.AddMvc();
            services.AddSingleton<IMyReminders,MyReminders>();
        }

        public void Configure(IApplicationBuilder app) {
            app.UseMvc();
        }
    }
}

Notice I also registered a custom service with the ASP.NET Core Dependency Injection Framework: MyReminders. This is a repository containing the reminders. This service is used in the Web API Controller.

services.AddSingleton<IMyReminders,MyReminders>();

That does it for the configuration, now I can create the Web API Controller.

ASP.NET Core Web API Controller

I write a Web API Controller that allows me to list, add, and remove reminders. I am using HTTP Get to retrieve the list of reminders, HTTP Post to add a reminder, and HTTP Delete to remove a reminder.

using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using RemindersSvc.Services;

namespace RemindersSvc.Contollers {
    [Route("api/[controller]")]
    public class RemindersController : Controller {
        private readonly IMyReminders myReminders;

        public RemindersController(IMyReminders reminders) {
            myReminders = reminders;
        }

        [HttpGet]
        public IEnumerable<string> Get() {
            return myReminders.FetchAll();
        }

        [HttpPost]
        public void Post([FromBody]string reminder) {
            myReminders.Add(reminder);
        }

        [HttpDelete]
        public void Remove([FromBody]string reminder) {
            myReminders.Remove(reminder);
        }
    }
}

MyReminders - Reminders Repository

The Reminders Controller delegates all the work to MyReminders, which is responsible for keeping track of the reminders. I am using a HashSet in C# to store the reminders in memory. I added MyReminders to the ASP.NET Core Dependency Injection Framework as a Singleton, because it is an in-memory repository and I need it available for the life of the application.

namespace RemindersSvc.Services {
    public interface IMyReminders {
        string[] FetchAll();
        void Add(string reminder);
        void Remove(string reminder);
    }
}
using System.Collections.Generic;
using System.Linq;

namespace RemindersSvc.Services {
    public class MyReminders : IMyReminders {
        private readonly HashSet<string> _reminders;

        public MyReminders() {
            _reminders = new HashSet<string> {
                "Meditate",
                "Eat a nutritious breakfast",
                "Relax with a cup of tea",
                "Be thankful",
                "Make the most of my day"
            };
        }
        public string[] FetchAll() {
            return _reminders.ToArray();
        }

        public void Add(string reminder) {
            _reminders.Add(reminder);
        }

        public void Remove(string reminder) {
            _reminders.Remove(reminder);
        }
    }
}

Run ASP.NET Core Web API Application on macOS

When I build and run the ASP.NET Core Web API Application on my MacBook Pro it starts successfully. I first build the .NET Core Application (dotnet build) and then run it (dotnet run), but that was just as an exemple because dotnet run will automatically do a build before it runs if necessary.

dotnet build

Project RemindersSvc (.NETCoreApp,Version=v1.0) will be compiled because inputs were modified
Compiling RemindersSvc for .NETCoreApp,Version=v1.0

Compilation succeeded.
    0 Warning(s)
    0 Error(s)

Time elapsed 00:00:01.1241653
 

dotnet run
Project RemindersSvc (.NETCoreApp,Version=v1.0) was previously compiled. Skipping compilation. Hosting environment: Production Content root path: /Users/Sasquatch/Projects/Core/RemindersSvc Now listening on: http://localhost:5000 Application started. Press Ctrl+C to shut down.

Python Web Client

I am currently learning Python as well as ASP.NET Core, so of course I will sneak both into all articles if possible :) Now I write a simple Python script to list, add, and remove reminders from the ASP.NET Core Web API Application.

import requests


def display_all_reminders():
    r = requests.get('http://localhost:5000/api/reminders')

    reminders = r.json()

    for reminder in reminders:
        print reminder
    print '----------'


# get reminders
display_all_reminders()

# add reminder
requests.post('http://localhost:5000/api/reminders', json='Exercise')
display_all_reminders()

# remove reminder
requests.delete('http://localhost:5000/api/reminders', json='Exercise')
display_all_reminders()

I am using the Python Requests HTTP Library to list all the current reminders, add an "Exercise" reminder, and then remove the new "Exercise" reminder. Here is the ouput.

Meditate
Eat a nutritious breakfast
Relax with a cup of tea
Be thankful
Make the most of my day
----------
Meditate
Eat a nutritious breakfast
Relax with a cup of tea
Be thankful
Make the most of my day
Exercise
----------
Meditate
Eat a nutritious breakfast
Relax with a cup of tea
Be thankful
Make the most of my day
----------

Conclusion

I hope this article on ASP.NET Core Web API is useful. I will be writing many more examples on ASP.NET Core MVC and Python on this website. Follow me on twitter to stay up-to-date on my articles and chat. Best wishes.

Posted by Koder Dojo

Wecome to Koder Dojo! I am a freelance C# ASP.NET MVC Developer learning ASP.NET Core MVC and Python. I am taking several online computer science and Python courses on algorithms, data structures, and cryptography while learning ASP.NET Core on my own. Many of my articles will be based on my answers to exercises and problem sets in my classes as well as programs and websites I dream up. This website is a daily journal of my adventures. It helps me retain my knowledge and I hope it helps and inspires others.

Related Posts: