Paul Ruiz
Paul Ruiz

Reputation: 2436

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.

Upvotes: 4

Views: 4090

Answers (2)

narancs
narancs

Reputation: 5294

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);

Upvotes: 2

Code-Apprentice
Code-Apprentice

Reputation: 83557

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.

Upvotes: 4

Related Questions