# Clean Code in ASP.NET Core: How to Write Clean and Maintainable REST APIs

**REST APIs are now at the heart of many modern applications. Writing clean, clear, and easily maintainable APIs is essential to ensure scalability, ease of development, and a reliable user experience.**

In this article, we will look at best practices to create REST APIs in [ASP.NET](http://ASP.NET) Core that follow clean code principles.

---

## Organize the project well

A clear structure helps maintain order and facilitates collaboration.

**Tips:**

* Divide the project into folders/logical layers such as Controllers, Services, Repositories, Models, DTOs.
    
* Keep business logic out of the controllers.
    
* Use consistent and meaningful naming (e.g., OrderController, IOrderService, OrderDto).
    

---

## Keep controllers slim and focused

Controllers should orchestrate calls to services and return responses, not contain complex logic.

```csharp
[ApiController]
[Route("api/[controller]")]
public class OrdersController : ControllerBase
{
    private readonly IOrderService _orderService;

    public OrdersController(IOrderService orderService)
    {
        _orderService = orderService;
    }

    [HttpGet("{id}")]
    public IActionResult GetOrder(int id)
    {
        var order = _orderService.GetOrderById(id);
        if (order == null) return NotFound();

        return Ok(order);
    }
}
```

---

## Use DTOs for input/output

Do not expose database entities directly.  
DTOs (Data Transfer Objects) allow separating the domain model from the API contracts.

```csharp
public class OrderDto
{
    public int Id { get; set; }
    public string CustomerName { get; set; }
    // other necessary fields
}
```

---

## Validation handling

**Data Annotations**

```csharp
public class CreateOrderDto
{
    [Required]
    public string CustomerName { get; set; }

    [Range(1, int.MaxValue)]
    public int Quantity { get; set; }
}
```

[ASP.NET](http://ASP.NET) Core automatically validates models when using `[ApiController]`.

**FluentValidation (optional)**

Use for more complex validations or business rules.

---

## Error handling and consistent responses

* Use appropriate HTTP status codes (200 OK, 201 Created, 400 Bad Request, 404 Not Found, 500 Internal Server Error).
    
* Return clear and consistent error messages.
    
* Centralize error handling using middleware (e.g., `UseExceptionHandler`).
    

---

## Logging and monitoring

Integrate logging with `ILogger<T>` to track important events and facilitate debugging.

---

## API testing

* Write automated tests for controllers and services.
    
* Use tools like Postman or Swagger for manual testing and documentation.
    

---

## Conclusion

Following these best practices helps you create REST APIs in [ASP.NET](http://ASP.NET) Core that are clean, maintainable, and scalable, respecting clean code principles and a solid architecture.
