Поиск  
Always will be ready notify the world about expectations as easy as possible: job change page
Jan 13, 2024

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

Create Todo REST API using .NET Core and Entity Framework with PostgreSQL
Автор:
Источник:
Просмотров:
4157
Create Todo REST API using .NET Core and Entity Framework with PostgreSQL favorites 0

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!

Похожее
Mar 9, 2023
Author: Vithal Wadje
ASP.NET Core Blazor Server is a platform for developing modern and dynamic web applications. With Blazor Server, you can write code in C# and create rich user interfaces using HTML and CSS, all while taking advantage of server-side rendering and...
Feb 7, 2021
Author: Sahan Serasinghe
Caching is the process of storing the data that’s frequently used so that data can be served faster for any future requests. Suppose we have a very lightweight process which talks to another server whose data is not going to...
Sep 9, 2024
Author: Stefan Đokić
Delve into securing .NET REST APIs against cyber threats with a focus on JWT, OAuth, SSL/TLS, and role-based authorization. This guide emphasizes for real-time monitoring and security assessments, ensuring your API's integrity and user data protection. Introduction In the digital...
Nov 20, 2022
Author: Juldhais Hengkyawan
Sometimes we have to perform several queries to the database, put the results into memory, and then process them as needed. For example, we have a Supplier table and a Customer table. Both tables have a substantial amount of data....
Написать сообщение
Тип
Почта
Имя
*Сообщение
RSS
Если вам понравился этот сайт и вы хотите меня поддержать, вы можете
Soft skills: 18 самых важных навыков, которыми должен владеть каждый работник
Зачем нужен MediatR?
Текстовый редактор для Git в среде Windows
Использование SQLite в .NET приложениях
Мультитаскинг, или Как работать над несколькими проектами и не сойти с ума
Какого черта мы нанимаем, или осмысленность собеседований в IT
Проблема понимания существующего кода, или Как делать иногда [не] надо
Как мы столкнулись с версионированием и осознали, что вариант «просто проставить цифры» не работает
Почему сеньоры ненавидят собеседования с кодингом, и что компании должны использовать вместо них
Функции и хранимые процедуры в PostgreSQL: зачем нужны и как применять в реальных примерах
Boosty
Donate to support the project
GitHub account
GitHub profile