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

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!

Похожее
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...
Jul 29
Author: Rick Strahl
Over the last few years, Markdown has become a ubiquitous text-entry model for HTML text. It's creeping up in more and more places and has become a standard for documents that are shared and edited for documentation purposes on the...
Aug 15
Author: Jigar Shah
In this comprehensive tutorial, you’ll discover the step-by-step process to build a simple REST API using PHP and MySQL. In the modern-day web landscape, REST APIs are extensively utilized for accessing and manipulating data. By incorporating REST APIs into the...
Sep 9
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...
Написать сообщение
Тип
Почта
Имя
*Сообщение
RSS
Если вам понравился этот сайт и вы хотите меня поддержать, вы можете
Soft skills: 18 самых важных навыков, которыми должен владеть каждый работник
101 вопрос, на которые должен ответить Python-разработчик
10 историй, как «валят» айтишников на технических интервью
Как мы столкнулись с версионированием и осознали, что вариант «просто проставить цифры» не работает
Переход от монолита к микросервисам: история и практика
Жесткие факты о софт скилах
Performance review, ачивки и погоня за повышением грейда — что может причинить боль сотруднику IT-компании?
Почему в вашем коде так сложно разобраться
Асинхронный JavaScript: изучаем Async/Await, Callbacks и Promises
9 главных трендов в разработке фронтенда в 2024 году
LinkedIn: Sergey Drozdov
Boosty
Donate to support the project
GitHub account
GitHub profile