Android API Integration (REST API)
Android API Integration (REST API)
Android-இல் REST API பயன்பாட்டின் மூலம் வெளி தரவுகளை (external data) எளிதில் பெற்றுக்கொள்ளலாம்.
உதாரணமாக, Weather App, News App, அல்லது Social Media Integration.
REST API என்றால் என்ன?
REST (Representational State Transfer) என்பது HTTP protocol மூலம் client ↔ server இடையே தரவு பரிமாற்றம் செய்யும் முறையாகும்.
பொதுவாக JSON வடிவில் தரவு அனுப்பப்படுகிறது.
Android-இல் API Integration செய்வது எப்படி?
- OkHttp → Lightweight HTTP client
- Volley → Google library, fast network operations
- Retrofit → Most popular, easy JSON parsing
1. OkHttp Example
// build.gradle dependency:
// implementation 'com.squareup.okhttp3:okhttp:4.9.3'
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://api.example.com/data")
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
String json = response.body().string();
Log.d("API", json);
}
}
});
2. Volley Example
// build.gradle dependency:
// implementation 'com.android.volley:volley:1.2.1'
String url = "https://api.example.com/data";
RequestQueue queue = Volley.newRequestQueue(this);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
response -> Log.d("API", response.toString()),
error -> error.printStackTrace()
);
queue.add(request);
3. Retrofit Example
Retrofit மிகவும் பிரபலமானது. API endpoints-ஐ interface ஆக 정의 செய்யலாம்.
// build.gradle dependencies:
// implementation 'com.squareup.retrofit2:retrofit:2.9.0'
// implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
public interface ApiService {
@GET("weather")
Call<WeatherResponse> getWeather(@Query("q") String city, @Query("appid") String key);
}
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.openweathermap.org/data/2.5/")
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiService api = retrofit.create(ApiService.class);
api.getWeather("Chennai","YOUR_API_KEY").enqueue(new Callback<WeatherResponse>() {
@Override
public void onResponse(Call<WeatherResponse> call, Response<WeatherResponse> response) {
if (response.isSuccessful()) {
WeatherResponse weather = response.body();
Log.d("API", "Temp: " + weather.getMain().getTemp());
}
}
@Override
public void onFailure(Call<WeatherResponse> call, Throwable t) {
t.printStackTrace();
}
});
JSON Parsing
JSON data-வை parse செய்ய GSON (Java) அல்லது Kotlin Serialization பயன்படுத்தலாம்.
உதாரணம்: Weather App
- OpenWeatherMap API-க்கு free API key பெறுங்கள்
- Retrofit மூலம் city பெயரை அனுப்புங்கள்
- Response JSON-இல் இருந்து Temperature, Humidity values எடுக்கவும்
- UI-இல் காட்டவும்
அதுவே! 🎉 இப்போது நீங்கள் Android App-இல் எந்த REST API-யையும் இணைக்கலாம்.
Comments
Post a Comment