ASP.NET Core Web API Interview Question #23
Why should API endpoints avoid exposing EF Core entities directly?
Web API & REST Fundamentals, Controllers, HTTP Methods & Status Codes Junior Beginner
Quick Interview Answer
Persistence entities are designed around database and domain concerns, while API contracts are designed for clients. Returning entities directly can expose internal fields, create serialization problems with navigation properties, encourage overposting, and tightly couple the API to the database model.
Detailed Explanation
Persistence entities are designed around database and domain concerns, while API contracts are designed for clients. Returning entities directly can expose internal fields, create serialization problems with navigation properties, encourage overposting, and tightly couple the API to the database model.
Mapping entities to response DTOs and request DTOs creates a deliberate boundary between storage and the external API.
Code Example
var response = new ProductResponse
{
Id = product.Id,
Name = product.Name,
Price = product.Price
};
return Ok(response);