Поиск  
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
Автор:
Источник:
Просмотров:
2927

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!

Похожее
May 4, 2023
Author: Sashko Stubailo
Often, GraphQL is presented as a revolutionary new way to think about APIs. Instead of working with rigid server-defined endpoints, you can send queries to get exactly the data you’re looking for in one request. And it’s true — GraphQL...
Oct 24, 2022
Author: Anton Shyrokykh
Entity Framework Core is recommended and the most popular tool for interacting with relational databases on ASP NET Core. It is powerful enough to cover most possible scenarios, but like any other tool, it has its limitations. Long time people...
Jun 26, 2021
There are many benefits to adding a React application to your ASP.NET Core application. The fact that you can house your front-end React tools with your API .NET tools in one application has to be one of the biggest. So...
Apr 1
Author: Ravindra Devrani
Fluent validation is a third party library for validating your models in .NET. It is totally free. Why fluent validation? If you already have used data annotation for validation, then you must be aware of validation in .NET. So you...
Написать сообщение
Тип
Почта
Имя
*Сообщение