Asp.Net Core 5 Rest API Step by Step
Tags: dotnet, beginners, rest
Published: 2021-01-19 08:17:55

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:
{% youtube p_wUdWshYc8 %}

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

This is Part 1 of API dev series:
- Part 2:https://dev.to/moe23/asp-net-core-5-rest-api-authentication-with-jwt-step-by-step-140d
- Part 3: https://dev.to/moe23/refresh-jwt-with-refresh-tokens-in-asp-net-core-5-rest-api-step-by-step-3en5

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/2y624yffje41tclunrjo.png)

The 4 things that we will need before we start:

- Visual Studio code (https://code.visualstudio.com/)
- Dotnet core SDK (https://dotnet.microsoft.com/download)
- Postman (https://www.postman.com/downloads/)
- DBeaver (https://dbeaver.io/download/)

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

```bash
dotnet --version
```

Now we need to install the entity framework tool

```bash
dotnet tool install --global dotnet-ef
```

Once thats finish we need to create our application

```bash
   dotnet new webapi -n "TodoApp" -lang "C#" -au none
```

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

```bash
dotnet add package Microsoft.EntityFrameworkCore.Sqlite
dotnet add package Microsoft.EntityFrameworkCore.Tools
```

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

```bash
dotnet build
dotnet run
```

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

```csharp
[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");
    }
}
```

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

```bash
dotnet build
dotnet run
```

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.

```csharp
public class ItemData
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Details { get; set; }
    public bool Done { get; set; }
}
```

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.

```csharp
public class ApiDbContext: DbContext
{
    public DbSet<ItemData> Items {get;set;}
    
    public ApiDbContext(DbContextOptions<ApiDbContext> options) : base(options)
    {
        
    }
    
}
```

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

```json
"ConnectionStrings": {
    "DefaultConnection": "DataSource=app.db;Cache=Shared"
  },
```

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.

```csharp
services.AddDbContext<ApiDbContext>(options =>
                options.UseSqlite(
                    Configuration.GetConnectionString("DefaultConnection")));
```

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

```bash
dotnet ef migrations add "Initial Migrations"
dotnet ef database update
```

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

```csharp
[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);
    }
}
```

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:
- Part 2:https://dev.to/moe23/asp-net-core-5-rest-api-authentication-with-jwt-step-by-step-140d
- Part 3: https://dev.to/moe23/refresh-jwt-with-refresh-tokens-in-asp-net-core-5-rest-api-step-by-step-3en5