Membuat API menggunakan ASP.NET Core 6.0

Membuat Project

1. Pertama Kita Pilih ASP.NET Core App (Model-View-Controller)

2. Masukkan nama Project & lokasi Project

3. Kita pilih .NET versi 6.0

Menginstall Nuget

Pilih Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution

Install Nuget berikut :

Swashbuckle.AspNetCore
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Tools

Membuat Database, Model, Context & Mengubungkan ke Database

  1. Buat database nya dulu di SQL Server dengan nama DemoApi

2. Setting appsettings.json

untuk setting Server & Database

 "ConnectionStrings": {
    "AppDb": "Server=.\\{NamaServer};Database={NamaDatabase};Trusted_Connection=True"
  }

3. Buat model dengan nama Employee

Di Class Employee masukkan Code berikut :

 public class Employee
    {
        [Key] // Set menjadi Primary Key
        public Guid Id { get; set; } = Guid.NewGuid();

        [Column(TypeName = "varchar")] // Set type data varchar
        [StringLength(10)] // Set panjang type datanya
        public string Username { get; set; } = null!;

        [Column(TypeName = "varchar")]
        [StringLength(200)]
        public string Email { get; set; } = null!;

        [JsonIgnore] // Agar tidak dibaca di Response API
        [Column(TypeName = "varchar")]
        [StringLength(200)]
        public string Password { get; set; } = null!;

        [Column(TypeName = "varchar")]
        [StringLength(10)]
        public string Firstname { get; set; } = null!;

        [Column(TypeName = "varchar")]
        [StringLength(50)]
        public string Lastname { get; set; } = null!;

        [Column(TypeName = "varchar")]
        [StringLength(250)]
        public string? EmployeeImage { get; set; }

        [Column(TypeName = "date")]
        [DataType(DataType.Date)]
        public DateTime DateOfBirth { get; set; }
    }

4. Buat Context dengan nama DemoApiContext

Pertama kita inherit class kita ke DbContext

public class DemoApiContext : DbContext {

}

Setelah itu Kita buat 2 contructor, biar lebih mudah tekan CTRL + . lalu pilih keduanya seperti gambar dibawah ini

Lalu Generate method OnConfiguring dengan menekan CTRL + . lalu pilih Generate overrides, lalu centang OnConfiguring seperti gambar dibawah

Jika sudah akan menjadi code berikut

public class DemoApiContext : DbContext 
    {
        private readonly string connectionString = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build().GetSection("ConnectionStrings")["AppDb"]; // samakan dengan appssettings.json

        public DemoApiContext(DbContextOptions options) : base(options)
        {
        }

        protected DemoApiContext()
        {
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            base.OnConfiguring(optionsBuilder);
        }

        public virtual DbSet<Employee> Employees { get; set; }
    }

5. Setting di Program.cs

masukkan code berikut:

var connectionString = builder.Configuration.GetConnectionString("AppDb"); // samakan namanya yg ada di appsettings.json
builder.Services.AddDbContext<DemoApiContext>(a => a.UseSqlServer(connectionString));

6. Migrasi Model ke Database

Pilih Tools -> NuGet Package Manager -> Package Manager Console

lalu masukkan perintah berikut:

Enable-Migrations

Add-Migration "MigrationName"

Update-Database

setelah itu akan terbuat table di SQL Server

Membuat Response

Kita akan membuat Response Api dengan format berikut:

 {
    "code": 200,
    "status": false,
    "message": "Pesan",
    "data": "Hasil Data Request"
  }

Buat Class baru dengan nama ResponseModel

masukkan code berikut:

  public class ResponseModel
    {
        public int Code { get; set; }

        public bool Status { get; set; }

        [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] // Kalo Messagenya Kosong tidak akan muncul di response
        public string Message { get; set; }

        [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] // Kalo Datanya Kosong tidak akan muncul di response
        public object Data { get; set; }
    }

Membuat Controller & Service

Buat Controller baru dengan nama EmployeesController

Buat Class dengan nama EmployeeService

Di Controller kita akan mengreturn data dari EmployeeService

Code di EmployeesController

    [Route("api/employee")] // ubah endpointnya menjadi api/employee
    [ApiController]
    public class EmployeesController : ControllerBase
    {
        private EmployeeService service;

        // Buat Constructor dengan parameter Context
        public EmployeesController(DemoApiContext db)
        {
            service = new EmployeeService(db);
        }

        [HttpGet]
        public async Task<IActionResult> GetEmployee()
        {
            try
            {
                var result = await service.GetEmployee();
                if (result.Code == StatusCodes.Status500InternalServerError) return StatusCode(500, result);
                return Ok(result);
            }
            catch (Exception ex)
            {
                return StatusCode(500, ex.Message);
            }
        }

        [HttpGet]
        [Route("{id}")]
        public async Task<IActionResult> GetEmployeeById(Guid id)
        {
            try
            {
                var result = await service.GetEmployeeById(id);
                if (result.Code == StatusCodes.Status500InternalServerError) return StatusCode(500, result);
                if (result.Code == StatusCodes.Status404NotFound) return NotFound(result);
                return Ok(result);
            }
            catch (Exception ex)
            {
                return StatusCode(500, ex.Message);
            }
        }

        [HttpPost]
        public async Task<IActionResult> PostEmployee(EmployeeViewModel request)
        {
            try
            {
                var result = await service.PostEmployee(request);
                if (result.Code == StatusCodes.Status500InternalServerError) return StatusCode(500, result);
                if (result.Code == StatusCodes.Status409Conflict) return Conflict(result);
                return Created("DemoApi", result);
            }
            catch (Exception ex)
            {
                return StatusCode(500, ex.Message);
            }
        }

        [HttpPut]
        [Route("{id}")]
        public async Task<IActionResult> PutEmployee(Guid id, EmployeeViewModel request)
        {
            try
            {
                var result = await service.PutEmployee(id, request);
                if (result.Code == StatusCodes.Status500InternalServerError) return StatusCode(500, result);
                if (result.Code == StatusCodes.Status409Conflict) return Conflict(result);
                if (result.Code == StatusCodes.Status404NotFound) return NotFound(result);
                return NoContent();
            }
            catch (Exception ex)
            {
                return StatusCode(500, ex.Message);
            }
        }

        [HttpDelete]
        [Route("{id}")]
        public async Task<IActionResult> DeleteEmployee(Guid id)
        {
            try
            {
                var result = await service.DeleteEmployee(id);
                if (result.Code == StatusCodes.Status500InternalServerError) return StatusCode(500, result);
                if (result.Code == StatusCodes.Status404NotFound) return NotFound(result);
                return Ok();
            }
            catch (Exception ex)
            {
                return StatusCode(500, ex.Message);
            }
        }
    }

Code di EmployeeService:

public class EmployeeService
    {
        private DemoApiContext db;
        private ResponseModel result = new ResponseModel();

        public EmployeeService(DemoApiContext db)
        {
            this.db = db;
        }

        public async Task<ResponseModel> GetEmployee()
        {
            try
            {
                var employees = await db.Employees.ToListAsync();

                response(result, 200, true, data: employees);
                return result;
            }
            catch (Exception ex)
            {
                response(result, 500, false, message: ex.Message);
                return result;
            }
        }

        public async Task<ResponseModel> GetEmployeeById(Guid id)
        {
            try
            {
                var employee = await db.Employees.Where(a => a.Id == id).FirstOrDefaultAsync();

                response(result, 200, true, data: employee);
                return result;
            }
            catch (Exception ex)
            {
                response(result, 500, false, message: ex.Message);
                return result;
            }
        }

        public async Task<ResponseModel> PostEmployee(EmployeeViewModel request)
        {
            try
            {
                var checkEmployeeUsername = await db.Employees.Where(a => a.Username == request.Username).FirstOrDefaultAsync();

                if (checkEmployeeUsername != null)
                {
                    response(result, 409, false, message: "Username already exist");
                    return result;
                }

                var emp = new Employee()
                {
                    Username = request.Username,
                    Email = request.Email,
                    DateOfBirth = request.DateOfBirth,
                    EmployeeImage = request.EmployeeImage,
                    Firstname = request.Firstname,
                    Lastname = request.Lastname,
                    Password = request.Password,
                };

                await db.Employees.AddAsync(emp);
                await db.SaveChangesAsync();

                response(result, 201, true, data: await db.Employees.FirstOrDefaultAsync(a => a.Id == emp.Id));
                return result;
            }
            catch (Exception ex)
            {
                response(result, 500, false, message: ex.Message);
                return result;
            }
        }

        public async Task<ResponseModel> PutEmployee(Guid id, EmployeeViewModel request)
        {
            try
            {
                var checkEmp = await db.Employees.Where(a => a.Id == id).FirstOrDefaultAsync();
                var checkEmpUsername = await db.Employees.Where(a => a.Username == request.Username).FirstOrDefaultAsync();

                if (checkEmp == null)
                {
                    response(result, 404, false, message: "Employee Id not found");
                    return result;
                }

                if (checkEmp.Username != request.Username)
                {
                    if (checkEmpUsername != null)
                    {
                        response(result, 409, false, message: "Username already exist");
                        return result;
                    }

                    checkEmp.DateOfBirth = request.DateOfBirth;
                    checkEmp.Username = request.Username;
                    checkEmp.Email = request.Email;
                    checkEmp.Firstname = request.Firstname;
                    checkEmp.Lastname = request.Lastname;
                    checkEmp.Password = request.Password;
                    checkEmp.EmployeeImage = request.EmployeeImage;
                }
                else
                {
                    checkEmp.DateOfBirth = request.DateOfBirth;
                    checkEmp.Email = request.Email;
                    checkEmp.Firstname = request.Firstname;
                    checkEmp.Lastname = request.Lastname;
                    checkEmp.Password = request.Password;
                    checkEmp.EmployeeImage = request.EmployeeImage;
                }

                await db.SaveChangesAsync();

                response(result, 204, true);
                return result;
            }
            catch (Exception ex)
            {
                response(result, 500, false, message: ex.Message);
                return result;
            }
        }

        public async Task<ResponseModel> DeleteEmployee(Guid id)
        {
            try
            {
                var checkEmployee = await db.Employees.Where(a => a.Id == id).FirstOrDefaultAsync();

                if (checkEmployee == null)
                {
                    response(result, 404, false, message: "Employee Id not found");
                    return result;
                }

                db.Employees.Remove(checkEmployee);
                await db.SaveChangesAsync();

                response(result, 200, true, message: "Successfully deleted the Employee");
                return result;
            }
            catch (Exception ex)
            {
                response(result, 500, false, message: ex.Message);
                return result;
            }
        }

        private void response(ResponseModel response, int code, bool status, object? data = null, string? message = null)
        {
            response.Code = code;
            response.Status = status;
            response.Data = data;
            response.Message = message;
        }
    }

Setting Swagger

Tambahkan Code berikut di Program.cs

builder.Services.AddSwaggerGen(a =>
{
    a.SwaggerDoc("v1", new OpenApiInfo
    {
        Title = "DemoApi",
        Description = "Simple ASP.NET Core API",
        Version = "v1",
    });
});

app.UseSwagger();
app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("v1/swagger.json", "DemoApi v1");
});

Test API

Jika sudah Kita jalankan

lalu akses swagger dengan menambahkan https://localhost:{port}/swagger/index.html

POST

Request Body:

{
  "username": "argi",
  "email": "argiiippp@gmail.com",
  "password": "123",
  "firstname": "Argi",
  "lastname": "Purwanto",
  "employeeImage": "image.png",
  "dateOfBirth": "2022-02-10"
}

Response Body:

{
  "code": 201,
  "status": true,
  "data": {
    "id": "638eb168-ee13-437e-bd7e-b65086b3dd11",
    "username": "argi",
    "email": "argiiippp@gmail.com",
    "firstname": "Argi",
    "lastname": "Purwanto",
    "employeeImage": "image.png",
    "dateOfBirth": "2022-02-10T00:00:00"
  }
}

GET

Response Body:

{
  "code": 200,
  "status": true,
  "data": [
    {
      "id": "638eb168-ee13-437e-bd7e-b65086b3dd11",
      "username": "argi",
      "email": "argiiippp@gmail.com",
      "firstname": "Argi",
      "lastname": "Purwanto",
      "employeeImage": "image.png",
      "dateOfBirth": "2022-02-10T00:00:00"
    }
  ]
}

PUT

masukkan Path Id Sebelumnya kita POST

Request Body:

{
  "username": "joko",
  "email": "joko@gmail.com",
  "password": "12345",
  "firstname": "Joko",
  "lastname": "Purnomo",
  "employeeImage": "image.png",
  "dateOfBirth": "2022-02-10"
}

Response Body :

Jika kita Get Ulang:

Response Body:

{
  "code": 200,
  "status": true,
  "data": [
    {
      "id": "638eb168-ee13-437e-bd7e-b65086b3dd11",
      "username": "joko",
      "email": "joko@gmail.com",
      "firstname": "Joko",
      "lastname": "Purnomo",
      "employeeImage": "image.png",
      "dateOfBirth": "2022-02-10T00:00:00"
    }
  ]
}

DELETE

Masukkan Id yg tadi kita buat, lalu akan menghapus Employee yg kita buat tadi

Scaffolding

Ada cara yang mudah tanpa membuat Model & Context dengan menggunakan Scaffold

Pertama buat dulu Database dan Tablenya

lalu pergi ke Package Manager Console dan masukkan perintah berikut:

Scaffold-DbContext "Server=.\{NamaServer};Database={NamaDatabase};Trusted_Connection=True" Microsoft.EntityFrameworkCore.SqlServer -out Models

Leave a Reply

Your email address will not be published. Required fields are marked *