13 web service integration
TRANSCRIPT
Web Service IntegrationAnuchit [email protected]
REST API
A RESTful API takes advantage of HTTP methodologies.
● GET to retrieve a resource● PUT to change the state of or update a resource, which
can be an object, file or block● POST to create that resource● DELETE to remove it.
Request method example
● GET /person → list person● GET /person/id → list person with given id● POST /person → create new person● PUT /person/id → edit or update person with given id● DELETE /person/id → delete person with given id
JSON
JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write.
JSON Structure
● A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
● An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
Retrofit API Client
retrofit= new Retrofit.Builder().baseUrl("http://api.example.com/").addConverterFactory(GsonConverterFactory.create()).build();
Retrofit API Interface
public interface ApiInterface {
@GET("place")
Call<List<Person>> doGetPlaceList();
}
Note: request url → http://api.example.com/place
// Api callApiInterface apiInterface = ApiClient.getClient().create(ApiInterface.class);Call<List<Place>> call = apiInterface.doGetPlaceList();call.enqueue(new Callback<List<Place>>() {
@Overridepublic void onResponse(Call<List<Place>> call, Response<List<Place>> response) {
int statusCode = response.code();Log.d("TAG", "code = " + statusCode);List<Place> place = response.body();
adapter = new PlaceAdapter(place);recyclerView.setAdapter(adapter);
}
@Overridepublic void onFailure(Call<List<Place>> call, Throwable t) {
Log.d("TAG", "" + t.getMessage());}
});
API Call
Picasso
Picasso.with(context).load(image_url).error(R.drawable.placeholder_error).placeholder(R.drawable.placeholder).into(imageview);
Build.gradle
compile 'com.google.code.gson:gson:2.8.0'compile 'com.squareup.retrofit2:retrofit:2.2.0'compile 'com.squareup.retrofit2:converter-gson:2.2.0'compile 'com.squareup.picasso:picasso:2.5.2'
Tools
● Advance REST Client● JSONView● jsonlint.com● jsonschema2pojo.org
Codelab: Get data from JSON url
JSON url
https://raw.githubusercontent.com/anoochit/jsondata/master/data02.json
Codelab: Get data from REST API
REST API
https://warm-ridge-87805.herokuapp.com/place