What is the right design to have a spring Entity that is different than what the REST API returns?

rest api design example
hateoas
postman
rest api best practices 2019
rest api naming best practices
spring boot rest api best practices
rest api response format best practices
swagger

Right now, I have an @Entity say Car that has a certain set of attributes. This gets persisted into a database.

Now, in the @RestController, if I want to accept a Car parameter except for certain properties, how do I do that? Right now, I am creating a different class called CarInput that is the same as Car minus those properties.

Again, for REST API response, same thing. If I want to return a Car but with a certain field removed. Right now I created CarResponse as a model.

Is there a cleaner way to do this?

I'd make the case that your external representation and your internal storage should hardly ever be identical. Sure, there'll be significant overlap, but your database and your API should be as independent from each other as possible.

I'd say it's a good practice to have separate domain models for the model and view layer (read: two different Car classes, in different packages). You can use a mapping framework like Dozer or MapStruct to map back and forth between these different entity types.

What is the best way to return different types of ResponseEntity in , It also makes it easy for your API to have a uniform exception /spring-4/spring-4​-mvc-jsonp-example-with-rest-responsebody-responseentity. REST API Best Practices — Design Examples From Java and Spring Web Services In the last article in this series, check out REST API best practices and look at design examples from Java and Spring

There are two common approaches to such problem.

  1. Use @JsonIgnore on fields/getters that you want to exclude. However, this can lead to annotation hell or generally hard to read code.
@JsonIgnore
private String password;
  1. Create a DTO class that data would be deserialized from or serialized to. What I mean is that when some user makes a POST request with a car definition, it would be deserialized by spring to CarDto and then parsed by you in the service layer to the Car object which you could save to a database. Similarly, Car object would be parsed to CarDto if the user asks for a data.
    @GetMapping("/{userId}")
    UserDto getUser(@PathVariable Long userId) {
        return userService.getUser(userId);
    }

    @PostMapping
    UserDto addUser(@RequestBody UserDto userDto) {
        return userService.createUser(userDto);
    }

This one, on the other hand, could lead to a situation where you sometimes use a Dto and sometimes the class itself. Because of that, consider parsing to/from CarDto only in the controller layer (unlike in the example above)

Also it's good to avoid creating two classes in one file. It makes hard to find a desired class afterwards.

REST API Best Practices, Designing Great REST API is important to have great microservices. REST API Best Practices - With Design Examples from Java and Spring Web Services How you should implement filtering, sorting, paging and other actions? The service returns three users when we submit a GET request to it. A key design goal of Spring HATEOAS is to make it easier to do The Right Thing™. In this scenario, adding hypermedia to your service without hard coding a thing. At this stage, you’ve created a Spring MVC REST controller that actually produces hypermedia-powered content!

Tutorial, But that is not the only thing needed to make your service In other words, an upgrade to the server required an Imagine this design problem: You've rolled out a system with Id; @Data @Entity class Employee { private @Id each of your REST methods returns a proper response. Spring Boot is an opinionated framework that makes our life very easy since we don’t have to choose the versions of different dependencies based on the version of Spring framework, its all taken

Best practices for REST API design, Best practices on how to design REST APIs to be easy to understand, of the API and the clients that use them since it's different from what Instead, we should use the nouns which represent the entity that the We get comments on the article identified by articleId and then return it in the response. A proper REST API should have below components in response. Status Code; Response Body; Location to the resource which was altered(for example, if a resource was created, client would be interested to know the url of that location) The main purpose of ResponseEntity was to provide the option 3, rest options could be achieved without ResponseEntity.

Spring REST, Designing and implementing a beautiful RESTful API is no less than an art. We start modeling different resources that are of interest to our consumers. Often, these resources can be the application's domain or entities. will look at best practices for designing a RESTful API and implementing it using Spring technologies. Let's now have a look at a standard controller implementation, exposing the simple REST API for the Post resource. We're going to show here a few simple CRUD operations: create, update, get one and get all. And given the operations are pretty straightforward, we are especially interested in the Entity-DTO conversion aspects:

REST API Naming Conventions and Best Practices – REST API , Learn the rest api naming conventions and best practices during API design process. A resource is a conceptual mapping to a set of entities, not the entity that end-point is substantially different from the resource returned by the second end-point, Should the store endpoint have the GET method that returns everything  REST API Design Best Practices for Parameter and Query String Usage When we’re designing APIs the goal’s to give our users some amount of power over the service we provide. While HTTP verbs and resource URLs allow for some basic interaction, oftentimes it’s necessary to provide additional functionality or else the system becomes too

Comments
  • In an API that follows the REST architecture model you don't focus on types but on representation formats. Usually so called REST APIs use typed resources though instead of properly negotiating about the exchanged format. The documentation of the API becomes now the truth and must not change (as well as the API itself) as otherwise clients will break. With a mapping, as suggested by Sean, you should be able to transform your business object back and forth through the supported representations.
  • Ok that makes sense. So would you recommend that I have different model for REST input and output? For example, I dont want to accept userID as input since it's auto generated by the backend, but I do want to return userID as output.
  • What about code repeated for model and view layer? it would be a bad practice to have code repeated.even using tools automated that breaks en.wikipedia.org/wiki/Bridge_pattern in POO.
  • @erotsppa It seems you expose your Car model directly to the client. This is always bad. In general the main premise of a REST API should always be that a server is teaching a client what it can do next. This is similar to a typical Web pages where a server will provide you a form to enter data in and it will usually transfer that data as www-form-urlencoded and there mapped back to some internal business object. There are approaches for JSON based forms, such as hal+forms or siren, though they might not be widely accepted yet
  • @RomanVottner yes I'm now aware. But that's why I'm asking is it recommended that I create two models (one for database mapping) and (one for accepting input from REST). And then use MapStruct to map between the 2.
  • @erotsppa It is for sure preferable to exposing the model directly or using a tailor-made mapping. I.e. I work in the area of EDI for a company that act as a middleman between all those fancy ERP systems, each promoting their own custom format. It is cumbersome to exchange messages between all those systems so we have our own, huge, internal model where we map those format onto ours, process the request according to our model and map the result back to their expected model. this is not trivial though spares a lot of M:N mappings for each type
  • Thats exactly the kind of situation I find myself in. So for the userDto for example it doesn't have the property Id (because its auto generated with @GeneratedValue). So I don't want to accept it for addUser, but I do want to return it with getUser. Does that approach makes sense?
  • try @JsonIgnore(access = Access.READ_ONLY) fasterxml.github.io/jackson-annotations/javadoc/2.6/com/…