Why Exposing Persistence Entities in APIs Is a Dangerous Shortcut

Published: (December 28, 2025 at 02:48 AM EST)
2 min read
Source: Dev.to

Source: Dev.to

Example Controller

@PostMapping("/books")
public BookItem create(@RequestBody BookItem bookItem) {
    return bookService.save(bookItem);
}

Why It Felt Right

  • The entity already had all the fields.
  • No extra classes to write.
  • Faster development.
  • DTOs seemed like unnecessary boilerplate for a small project.

Problems with Exposing Entities Directly

When an entity is used directly as a request body, every field becomes writable. This allows a client to:

  • Set database IDs manually.
  • Modify fields they should never control.
  • Send values meant only for internal logic.

The framework simply maps fields without knowing the intent, so the API trusts the client far too much.

Entity‑Specific Concerns

  • Internal flags.
  • Audit timestamps.
  • Fields irrelevant or unsafe for clients.

Once clients start consuming these fields, they become part of the public contract—even if you never intended them to be. This is the most critical problem and often appears too late.

Example Entity and JSON Payload

@Entity
public class BookItem {
    @Id
    private String id;
    private String title;
    private String author;
    private int pages;
}
{
  "id": "123",
  "title": "Clean Code",
  "author": "Robert Martin",
  "pages": 464
}

Clients build their logic around this response.

Changing the Entity Breaks the API

Suppose you decide that pages is inaccurate and replace it with wordCount:

@Entity
public class BookItem {
    @Id
    private String id;
    private String title;
    private String author;
    private int wordCount;
}

You didn’t touch the controller, but the response now becomes:

{
  "id": "123",
  "title": "Clean Code",
  "author": "Robert Martin",
  "wordCount": 150000
}
  • pages disappeared.
  • wordCount appeared.

Result: Clients break, front‑ends crash, mobile apps fail. This happened because the entity was acting as the API.

Benefits of Using DTOs

DTOs create a stable boundary between internal models and external consumers.

  • Clients can send only allowed fields.
  • Responses expose only safe data.
  • Entities can change freely.
  • APIs remain stable.

Conclusion

Using entities directly in APIs may feel productive at first, but the real cost appears later—when requirements change and refactoring becomes risky. An entity is not an API. DTOs may add a few extra classes, but they protect your system from silent breakage and future pain.

Back to Blog

Related posts

Read more »

Stop Writing APIs Like It's 2015

We're in 2025, and many codebases still treat APIs as simple “endpoints that return JSON.” If your API design hasn’t evolved past basic CRUD routes, you’re sacr...