Warning: Trying to access array offset on value of type null in /home/customer/www/mozartec.com/public_html/wp-content/plugins/pressapps-login-access/includes/skelet/path.php on line 408
To Do Rest API Using Asp.net Core (Part 1) - Mozartec
Mozart Al Khateeb

Full Stack

Mobile

.Net Developer

ERP Developer

Mozart Al Khateeb

Full Stack

Mobile

.Net Developer

ERP Developer

Blog Post

To Do Rest API Using Asp.net Core (Part 1)

To Do Rest API Using Asp.net Core (Part 1)

In this post I will show you how to create a simple web API using Asp.Net Core and Entity Framework Core. Then in later posts we will extend this API by adding more features and show real examples on how we can consume this rest API using client side (mobile and web frameworks).

Creating a new project

Add reference via NuGet for: Install-Package Microsoft.EntityFrameworkCore.Sqlite -Version 2.2.4

https://www.nuget.org/packages/Microsoft.EntityFrameworkCore.Sqlite/

We will use SqLite as Db provider but Entity Framework core supports other Db providers that you can work with.

Coding

Creating Db Context and Entities

Entities

Create a new folder called Entities and add the following class in there.

ToDo.cs
using System.ComponentModel.DataAnnotations;

namespace ToDo.API.Entities
{
    public class ToDo
    {
        [Key]
        public int Id { get; set; }
        public string Description { get; set; }
        public string Status { get; set; }
    }
}
Db Context and Config

Create a new folder called Data and add the following classes in there.

Config.cs
using System.Collections.Generic;

namespace ToDo.API.Data
{
    public class Config
    {
        public static List<string> Statues = new List<string>
        {
            "Pending",
            "In Progress",
            "Done",
            "Cancelled"
        };
    }
}
AppDbContext.cs
using Microsoft.EntityFrameworkCore;

namespace ToDo.API.Data
{
    public class AppDbContext : DbContext
    {
        public DbSet<Entities.ToDo> ToDos { get; set; }

        public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
        {
        }
    }
}
SqLite Connection String
appsettings.json
{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "SqLite": "Data Source=ToDo.db;"
  }
}
Registering SqLite Db Provider
Startup.cs
        public void ConfigureServices(IServiceCollection services)
        {
            #region Registering DbContext
            services.AddDbContext<AppDbContext>(options =>
                options.UseSqlite(Configuration.GetConnectionString("SqLite"))); //SqLite Provider
            #endregion
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }
Generating the Database
Adding a new migration

In the NuGet Package Manages Console Type the following command and hist enter to generate a new Db Migration.

Add-Migration Initial

A migrations folder should now appear in your solution containing two classes that keep track of changes that you make to your DbContext and the connected Entities.

Applying the migration

In the NuGet Package Manages Console Type the following command and hist enter to generate a new Db using the provided connection string and the migration we generated earlier.

Update-Database

Now you should see a new database called ToDo.db appear at the root of your solution. you can use software like: SqLiteBrowser to browse the newly created database.

Creating our API End Points

Controllers

Place new Controllers inside the Controllers folder that was created by default.

Config
ConfigController.cs

Our first controller’s task for now is to retrieve the available Statuses that can be assigned to a ToDo item.

using Microsoft.AspNetCore.Mvc;
using ToDo.API.Data;

namespace ToDo.API.Controllers
{
    [Route("api/[controller]")]
    public class ConfigController : Controller
    {
        // GET: api/<controller>
        [HttpGet]
        public IActionResult Get()
        {
            return Ok(Config.Statues);
        }
    }
}

run the app and visit this end point: http://localhost:58635/api/config note that you might have to change the port number in case visual studio assigned a different port than mine. If you followed along you should see a JSON array with the available statuses.

ToDosController.cs

Instead of manually writing the code for our next controller, we are going to use visual studio scaffolding feature to generate the ToDos Controller.

Right click the Controllers folder click Add > Controller > you should a see a screen like this:

Select API Controller with actions, using Entity Framework, fill the values like the next screen and click Add.

This will create your new controller, if you see errors appearing in ToDosController class do not worry just add the missing reference for the ToDo Entity.

using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using ToDo.API.Data;

namespace ToDo.API.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ToDosController : ControllerBase
    {
        private readonly AppDbContext _context;

        public ToDosController(AppDbContext context)
        {
            _context = context;
        }

        // GET: api/ToDos
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Entities.ToDo>>> GetToDos()
        {
            return await _context.ToDos.ToListAsync();
        }

        // GET: api/ToDos/5
        [HttpGet("{id}")]
        public async Task<ActionResult<Entities.ToDo>> GetToDo(int id)
        {
            var toDo = await _context.ToDos.FindAsync(id);

            if (toDo == null)
            {
                return NotFound();
            }

            return toDo;
        }

        // PUT: api/ToDos/5
        [HttpPut("{id}")]
        public async Task<IActionResult> PutToDo(int id, Entities.ToDo toDo)
        {
            if (id != toDo.Id)
            {
                return BadRequest();
            }

            _context.Entry(toDo).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ToDoExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return NoContent();
        }

        // POST: api/ToDos
        [HttpPost]
        public async Task<ActionResult<Entities.ToDo>> PostToDo(Entities.ToDo toDo)
        {
            _context.ToDos.Add(toDo);
            await _context.SaveChangesAsync();

            return CreatedAtAction("GetToDo", new { id = toDo.Id }, toDo);
        }

        // DELETE: api/ToDos/5
        [HttpDelete("{id}")]
        public async Task<ActionResult<Entities.ToDo>> DeleteToDo(int id)
        {
            var toDo = await _context.ToDos.FindAsync(id);
            if (toDo == null)
            {
                return NotFound();
            }

            _context.ToDos.Remove(toDo);
            await _context.SaveChangesAsync();

            return toDo;
        }

        private bool ToDoExists(int id)
        {
            return _context.ToDos.Any(e => e.Id == id);
        }
    }
}

You can test out the API using postman: http://localhost:58635/api/ToDos

{
	"description": "Fix bugs",
	"status": "Pending"
}

I hope you found this post helpful, although post man is an important utility that every web developer should know how to use. In the next post I will show you another cool way for testing your web API easier using swagger.

Source Code

Taggs:
Write a comment