Advertisement
Search  
Always will be ready notify the world about expectations as easy as possible: job change page
Jan 13

Create Todo REST API using .NET Core and Entity Framework with PostgreSQL

Create Todo REST API using .NET Core and Entity Framework with PostgreSQL
Author:
Source:
Views:
524

In the world of web development, building robust and efficient REST APIs is a crucial skill. Whether you are a C# beginner or have some programming experience, creating RESTful APIs using .NET Core and Entity Framework with PostgreSQL is an excellent starting point to dive into backend development. .NET Core is a cross-platform, open-source framework that allows you to build modern applications, and Entity Framework simplifies the process of working with databases. In this tutorial, we will guide you through the step-by-step process of setting up a .NET Core project, integrating Entity Framework with PostgreSQL, and building a fully functional REST API. Let’s embark on this coding journey together!

Prerequisites

Before we get started, ensure that you have the following prerequisites installed on your system:

  1. .NET Core SDK: Download and install the latest version from the official .NET website.
  2. Visual Studio Code: Install VSCode, a lightweight yet powerful code editor, from the official VSCode website.
  3. PostgreSQL: Install PostgreSQL, an open-source relational database management system, and create a database for our project.

Getting started

Let’s begin by creating a new .NET Core Web API project. Open your terminal or command prompt and execute the following commands:

# Create a new .NET Core Web API project
dotnet new webapi -n MyRestApi
cd MyRestApi

This will create a new .NET Core Web API project named “MyRestApi” and navigate you to the project directory.

Installing Entity Framework Core

Next, we’ll install Entity Framework Core to enable database operations. In the terminal, run the following command:

# Install Entity Framework Core package
dotnet add package Npgsql.EntityFrameworkCore.PostgreSQL

This command installs the PostgreSQL database provider for Entity Framework Core. It allows us to interact with the PostgreSQL database seamlessly.

Setting up the database context

Now, let’s set up the database context to work with PostgreSQL. Create a new folder named “Data” in your project and add a new file named “AppDbContext.cs” with the following code:

// Data/AppDbContext.cs
using Microsoft.EntityFrameworkCore;

public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
    {
    }

    public DbSet<Todo> Todos { get; set; }
}

In the code above, we define an “AppDbContext” class that inherits from “DbContext.” The “AppDbContext” class contains a “DbSet” property for the “Todo” model, allowing us to perform database operations on the “Todo” table.

Configuring the database connection

Now, we need to configure the database connection in the “Startup.cs” file. Open the “Startup.cs” file in the root of your project and modify the “ConfigureServices” method as follows:

// Startup.cs
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;

public class Startup
{
    private readonly IConfiguration _configuration;

    public Startup(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    public void ConfigureServices(IServiceCollection services)
    {
        // Database connection with PostgreSQL
        services.AddDbContext<AppDbContext>(options =>
            options.UseNpgsql(_configuration.GetConnectionString("DefaultConnection")));

        // Other configurations
        services.AddControllers();
    }

    // Rest of the code
}

In the code above, we use the “Configuration” object to retrieve the connection string from the “appsettings.json” file. Make sure you have an “appsettings.json” file in your project root with the following content:

{
  "ConnectionStrings": {
    "DefaultConnection": "Host=localhost;Port=5432;Database=mydatabase;Username=myusername;Password=mypassword"
  },
  "Logging": {
    // Logging configurations (optional)
  },
  "AllowedHosts": "*"
}

Replace the placeholders localhost, 5432, mydatabase, myusername and mypassword with the appropriate values for your PostgreSQL database.

Creating a data model

Now that we have the database context set up, let’s create a simple data model. In this example, we’ll create a Todo model that represents a todo item with an Id and a Title.

Open the Model folder in your project and create a new file named Todo.cs with the following code:

// Models/Todo.cs
using System.ComponentModel.DataAnnotations;

public class Todo
{
    public int Id { get; set; }

    [Required]
    public string Title { get; set; }
}

In the code above, we define a “Todo” class with two properties: “Id” of type “int” and “Title” of type “string.” We also use data annotations to enforce that the “Title” property is required.

Implementing CRUD operations

With the database context, configuration, and data model set up, it’s time to implement CRUD (Create, Read, Update, Delete) operations for our “Todo” model.

Creating a Todo

Open the “Controllers” folder in your project and create a new file named “TodosController.cs” with the following code:

// Controllers/TodosController.cs
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

[ApiController]
[Route("api/[controller]")]
public class TodosController : ControllerBase
{
    private readonly AppDbContext _dbContext;

    public TodosController(AppDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    [HttpGet]
    public ActionResult<IEnumerable<Todo>> GetTodos()
    {
        return _dbContext.Todos.ToList();
    }

    [HttpGet("{id}")]
    public ActionResult<Todo> GetTodoById(int id)
    {
        var todo = _dbContext.Todos.Find(id);
        if (todo == null)
        {
            return NotFound();
        }
        return todo;
    }

    [HttpPost]
    public ActionResult<Todo> CreateTodo([FromBody] Todo todo)
    {
        _dbContext.Todos.Add(todo);
        _dbContext.SaveChanges();
        return CreatedAtAction(nameof(GetTodoById), new { id = todo.Id }, todo);
    }

    [HttpPut("{id}")]
    public IActionResult UpdateTodo(int id, [FromBody] Todo updatedTodo)
    {
        var todo = _dbContext.Todos.Find(id);
        if (todo == null)
        {
            return NotFound();
        }

        todo.Title = updatedTodo.Title;
        _dbContext.SaveChanges();
        return NoContent();
    }

    [HttpDelete("{id}")]
    public IActionResult DeleteTodo(int id)
    {
        var todo = _dbContext.Todos.Find(id);
        if (todo == null)
        {
            return NotFound();
        }

        _dbContext.Todos.Remove(todo);
        _dbContext.SaveChanges();
        return NoContent();
    }
}

In the code above, we’ve implemented the “TodosController” with endpoints for performing CRUD operations on the “Todo” model. The controller uses the “AppDbContext” to interact with the PostgreSQL database.

Testing the API

Now that we have implemented the CRUD operations, let’s test our API using a REST client like Postman.

1. Run your .NET Core application by executing the following command in your terminal or command prompt:

dotnet run

2. Open Postman or any REST client and send HTTP requests to the following endpoints:

  • GET http://localhost:5000/api/todos to get all todos.
  • GET http://localhost:5000/api/todos/{id} to get a todo by its id.
  • POST http://localhost:5000/api/todos with a JSON body containing the Title property to create a new todo.
  • PUT http://localhost:5000/api/todos/{id} with a JSON body containing the updated Title property to update a todo.
  • DELETE http://localhost:5000/api/todos/{id} to delete a todo by its id.

Conclusion

Congratulations! You have successfully created a REST API using .NET Core and Entity Framework with PostgreSQL. This tutorial provided a comprehensive guide for C# beginners to get started with backend development. With .NET Core’s versatility and Entity Framework’s ease of use, building efficient and scalable APIs becomes a breeze. Keep exploring and experimenting with different features of .NET Core and Entity Framework to further enhance your API and backend development skills. Happy coding and have fun building incredible RESTful APIs!

Similar
17 декабря 2014 г.
Краткий обзор .NET Core, как это соотносится с .NET Framework и что это все означает для кросс-платформенной разработки и разработки с открытым кодом.Взгляд назад – мотивация для .NET CoreПрежде всего, давайте оглянемся назад, чтобы понять, как платформа .NET была устроена...
Mar 29
Author: Colton
These interview questions range from basic to advanced .Net Core, and will assist you in preparing for interviews, revising quickly, and strengthening your technical skills.According to the Stackoverflow Survey 2020,.NET and.NET Core are the second and third most popular frameworks...
Apr 24, 2022
Author: Juan Alberto España Garcia
The security of .NET applications is necessary and knowing how to protect it is not always an easy task. As developers, we must be clear that an insecure application can be a serious problem: from modifying the operation of the...
Jun 25, 2022
Author: Philipp Bauknecht
Sometimes your web app needs to do work in the background periodically e.g. to sync data. This article provides a walkthrough how to implement such a background task and how to enabled/disable a background task during runtime using a RESTful...
Send message
Email
Your name
*Message


© 1999–2024 WebDynamics
1980–... Sergey Drozdov
Area of interests: .NET Framework | .NET Core | C# | ASP.NET | Windows Forms | WPF | HTML5 | CSS3 | jQuery | AJAX | Angular | React | MS SQL Server | Transact-SQL | ADO.NET | Entity Framework | IIS | OOP | OOA | OOD | WCF | WPF | MSMQ | MVC | MVP | MVVM | Design Patterns | Enterprise Architecture | Scrum | Kanban