DEV Community

Mohamad Lawand
Mohamad Lawand

Posted on • Updated on

Asp.Net Core 5 Rest API Step by Step

In this post we will be creating a simple Asp.Net Core Rest API Todo application where we will be able to add, edit, delete and view todo items and we will be utilising SQLite to store our data.

You can also watch the full step by step video on YouTube:

As well download the source code:
https://github.com/mohamadlawand087/v6-RestApiNetCore5

This is Part 1 of API dev series:

Alt Text

The 4 things that we will need before we start:

Once we have downloaded and installed all of the required tool, we need to make sure that the dotnet SDK has been installed successfully, we need to open the terminal and check if the dotnet SDK is installed successfully by checking the dotnet version

Open the terminal type the command below

dotnet --version
Enter fullscreen mode Exit fullscreen mode

Now we need to install the entity framework tool

dotnet tool install --global dotnet-ef
Enter fullscreen mode Exit fullscreen mode

Once thats finish we need to create our application

   dotnet new webapi -n "TodoApp" -lang "C#" -au none
Enter fullscreen mode Exit fullscreen mode

Now lets add the packages that we will nee in order of us to utilise the EntityFramrwork and SQLite

dotnet add package Microsoft.EntityFrameworkCore.Sqlite
dotnet add package Microsoft.EntityFrameworkCore.Tools
Enter fullscreen mode Exit fullscreen mode

Now lets open VS code and check our application and check the source code, lets build the application and see if its running

dotnet build
dotnet run
Enter fullscreen mode Exit fullscreen mode

We start by removing the default template code that was generated by the .Net core framework for us. Will dlete the WeatherForcastController and the WeatherForcast class.

Will create our own controller will call it TodoController.

Will create our first simple action will call it TestRun, lets start coding our controller

[Route("api/[controller]")] // We define the routing that our controller going to use
[ApiController] // We need to specify the type of the controller to let .Net core know
public class TodoController : ControllerBase
{
        [Route("TestRun")] // define the routing for this action
    [HttpGet]
    public ActionResult TestRun()
    {
        return Ok("success");
    }
}
Enter fullscreen mode Exit fullscreen mode

Once we finish adding we need to test it, in order for us to do that we need to do the following

dotnet build
dotnet run
Enter fullscreen mode Exit fullscreen mode

Once the application is running we need to open postman and try it there see we get the response.

we create a new request in postman and set the type to get and we add the following URL:

(https://localhost:5001/api/todo/)testrun as you can see from our test we get the success response inside postman.

After testing it we now need to start adding models, we add a models folder in the root directory and we add a class inside of it called Item. This is going to be a very simple model which represent our todo list item.

public class ItemData
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Details { get; set; }
    public bool Done { get; set; }
}
Enter fullscreen mode Exit fullscreen mode

once we add our model now we need to build our ApiDbContext. We need to create a Data folder in our root directory and inside this folder will create a new class called ApiDbContext.

public class ApiDbContext: DbContext
{
    public DbSet<ItemData> Items {get;set;}

    public ApiDbContext(DbContextOptions<ApiDbContext> options) : base(options)
    {

    }

}
Enter fullscreen mode Exit fullscreen mode

We need to specify our connection string inside the appsetting.json application

"ConnectionStrings": {
    "DefaultConnection": "DataSource=app.db;Cache=Shared"
  },
Enter fullscreen mode Exit fullscreen mode

Perfect once our DbContext and connection string is ready we need to update the startup class so we can utilise the Application DbContext inside our application. Open the startup class in our root folder and add the following code.

services.AddDbContext<ApiDbContext>(options =>
                options.UseSqlite(
                    Configuration.GetConnectionString("DefaultConnection")));
Enter fullscreen mode Exit fullscreen mode

Once we have add the DbContext middleware we need to add the initial migration to create the database.

dotnet ef migrations add "Initial Migrations"
dotnet ef database update
Enter fullscreen mode Exit fullscreen mode

After the database update has completed successfully we can see we have a new folder called migrations which will contain the C# script which will be responsible on creating the database and its table Item. we can verify that the database has been created since we can see the app.db file in our root directory as well we can see that use the SQLite browser to verify that the table has been created successfully.

Now that we have completed all of the infrastructure work for our controller. Now we need to start building our TodoController and connect it to the ApiDbContext.

Will start by adding the get all items in our todo list

[Route("api/[controller]")]
[ApiController]
public class TodoController : ControllerBase
{
    private readonly ApiDbContext _context;

    public TodoController(ApiDbContext context)
    {
        _context = context;
    }

    [HttpGet]
    public ActionResult GetItems()
    {
        var items = _context.Items.ToList();
        return Ok(items);
    }

    [HttpGet("{id}")]
    public async Task<IActionResult> GetItem(int id)
    {
        var item = await _context.Items.FirstOrDefaultAsync(z => z.Id == id);

        if(item == null)
            return NotFound();

        return Ok(item);
    }

    [HttpPost]
    public async Task<IActionResult> CreateItem(ItemData data)
    {
        if(ModelState.IsValid)
        {
           await _context.Items.AddAsync(data);
           await _context.SaveChangesAsync();

            return CreatedAtAction("GetItem", new {data.Id}, data);
        }

         return new JsonResult("Somethign Went wrong") {StatusCode = 500};
    }

    [HttpPut("{id}")]
    public async Task<IActionResult> UpdateItem(int id, ItemData item)
    {
        if(id != item.Id)
            return BadRequest();

        var existItem = await _context.Items.FirstOrDefaultAsync(z => z.Id == id);

        if(existItem == null)
            return NotFound();

        existItem.Title = item.Title;
        existItem.Details = item.Details;
        existItem.Completed = item.Completed;

        await _context.SaveChangesAsync();

                // Following up the REST standart on update we need to return NoContent
        return NoContent();
    }

    [HttpDelete("{id}")]
    public async Task<IActionResult> DeleteItem(int id)
    {
        var existItem = await _context.Items.FirstOrDefaultAsync(z => z.Id == id);

        if(existItem == null)
            return NotFound();

        _context.Items.Remove(existItem);
        await _context.SaveChangesAsync();

        return Ok(existItem);
    }
}
Enter fullscreen mode Exit fullscreen mode

We can test each one of these in postman.

Finally since we are using .Net 5 when creating webapi project Swagger will be already integrated within our application, in order for us to see the swagger interface we need to go to (http://localhost:5000/swagger/index.html)

Swagger allows you to describe the structure of your APIs so that machines can read them, at no extra work from our side other then defining swagger in older version of .net core swagger will be able to read our API structure and give us a UI that we can use to enhance our dev experience

Thank you for reading this article

This is Part 1 of API dev series:

Discussion (2)

Collapse
josemiralles profile image
Jose

There is something really special about seeing .Net core being developed on a Mac.

Collapse
olufemi_oyedepo profile image
Olufemi Oyedepo

Yea it's a bit dev-sexy!