Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Retrofit to Access an API with key/id

I haven't really found clear documentation on this, but I was wondering if anyone could point me towards something on using Retrofit (or OKHTTP or something if that's more appropriate) in order to pull down a JSON stream from an API that requires an API ID and API key (example accessing the data from terminal: curl -v -H "app_id:appid" -H "app_key:appkey" -X GET "http://data.leafly.com/strains/blue-dream" ).

I checked over the official documentation on Square's site, but if there's anything else out there that could help me just pull that data down that would be awesome.

Thanks!


Final answer

RestAdapter.Builder builder= new RestAdapter.Builder()
            .setEndpoint( "http://data.leafly.com/" )
            .setRequestInterceptor(new RequestInterceptor() {
                @Override
                public void intercept(RequestInterceptor.RequestFacade request) {
                    request.addHeader("app_id", "id");
                    request.addHeader("app_key", "key");
                }
            });

    final RestAdapter restAdapter = builder.build();

new Thread( new Runnable() {
        @Override
        public void run() {
            LeaflyService service = restAdapter.create(LeaflyService.class);
            final Strain strain = service.data("blue-dream");

            runOnUiThread( new Runnable() {
                @Override
                public void run() {
                    mText.setText( strain.getDescription() );
                }
            } );
        }
    } ).start();

plus the strain model, that just fits the data.

like image 965
Paul Ruiz Avatar asked Oct 31 '25 03:10

Paul Ruiz


2 Answers

To send the ID and key, you need to modify the HTTP headers. It appears that you can do this with the @Header annotation in Retrofit.

like image 144
Code-Apprentice Avatar answered Nov 01 '25 16:11

Code-Apprentice


the answer above didn`t work for me, here is my solution:

    RestAdapter.Builder adapterBuilder = new RestAdapter.Builder().setLogLevel(RestAdapter.LogLevel.FULL)
            .setEndpoint(BACKEND_URL).setRequestInterceptor(new RequestInterceptor() {
                @Override
                public void intercept(RequestInterceptor.RequestFacade request) {
                    request.addQueryParam("apikey", apiKey);
                }
            });
    service = adapterBuilder.build().create(BackendInterface.class);
@POST("/getall")
void getIdeaList( Callback<GetAllIdeaResponse> callback);
like image 44
narancs Avatar answered Nov 01 '25 16:11

narancs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!