3
I would like to know how to ignore a model attribute in a request POST
with Retrofit. In requests GET
I want to bring all attributes, but in requests POST
I need to send the object without the id
for example.
Example of Model:
public class Model {
int id; // ignorar este atributo
String atributo1;
String atributo2;
String atributo3; // ignorar este atributo
// ... getters and setters
}
Example of Service:
public interface ModelService {
@POST("resources")
Call<Model> create(@Body Model model) // enviar objeto sem id e atributo3
}
Example of execution:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
ModelService modelService = retrofit.create(ModelService.class);
Call<Model> call = modelService.create(collection);
call.enqueue(new Callback<Model>() {
// ... onResponse / onFailure
});
Is there such a possibility or do I need to implement it another way? Or maybe I should treat it on backend?
Out of curiosity, because you want to ignore the id of your entity ? it was always going like 0 and it was getting in your way ?
– wryel
You’re right, I thought the id 0 was impending the record to be created in the API, but I did a quick test and it worked. The problem is that in a requisition
GET
comes one or another value that is not of the model, but that is useful. For example, a task is performed in a city, then in a request to/tarefas
I bring the id and name of the city in json, but the name of the city is not part of the task, just the city id. So, in a requestPOST
, If the city name is in the body the record is not created. Maybe the correct thing is to treat it in the backend, I’m not sure.– Fernando Zabin
To maintain the high level and fluency of your api, you should return the Task object with a City object reference. But returning the city id is not wrong, it is only less fluent, both are absolutely correct.
– wryel
So it would be interesting to bring only the name of the city, since it is important in this request, and a reference (link) to the object city? This is Hypermedia, right? What about bringing the City object inside the Task object? I saw some examples like this.
– Fernando Zabin