2. About me
• Name: Kazuhiro Serizawa
• Job: Web engineer
• Like: RoR, AngularJS
• Github: serihiro
• Twitter: seri_k
• Blog: http://serihiro.hatenablog.com/
3. What is Retrofit?
• A type-safe REST client for Android and Java
• Created by Square, Inc.
• 5493 Starred (at 2015.5.25)
• Latest version is 1.9.0 (at 2015.5.25)
• Gtihub: https://github.com/square/retrofit
• Docs: http://square.github.io/retrofit/
4. How to use?
In the case you access to Todo API
GET /todo … response todo list with json
GET /todo/:id … response todo with json
POST /todo … create new todo resource
code sample
https://github.com/serihiro/retrofit-implement-samle
5. 1. Define API Interface
public interface TodoService {
@GET("/todos")
List<Todo> list();
@GET("/todos/{id}")
Todo show(@Path("id") Integer id);
@POST("/todos")
void create(@Body Todo todo);
}
6. 2. Implement model class
for API response
public class Todo {
public Integer id = null;
public String todo = "";
public boolean done = false;
public Todo(String todo, boolean done) {
this.todo = todo;
this.done = done;
}
}
7. 3. Generate implementation
for API interface
RestAdapter restAdapter = new
RestAdapter.Builder()
.setEndpoint( http://localhost:3000")
.build();
TodoService todoService =
restAdapter.create(TodoService.class);
8. 4.call api
List<Todo> todos = todoService.list();
Todo todo = todoService.show(1);
todoService.create(new Todo( drink beer , false));
10. Interface as API
Specification
• Client user can know what endpoint exists
• User get 404 with wrong endpoint name spell !!!
• No more almost correct API documents : )
public interface TodoService {
@GET("/todos")
List<Todo> list();
@GET("/todos/{id}")
Todo show(@Path("id") int id);
@POST("/todos")
void create(@Body Todo todo, Callback<Result> cb);
}
11. feature: ASYNC request
with callback
• Synchronous
• void create(@Body Todo todo)
• Asynchronous
• void create(@Body Todo todo,
Callback<Result> cb);
12. converters
Retrofit uses Gson to parse response body as a
default.
There are following converter class instead of Gson;
• Simple XML Parser(Uses simple framework)
• Jackson
• Google Protocol Buffer
• Wire
source: https://github.com/square/retrofit/tree/master/retrofit-converters