Free Source Code - Codeintra

Documentation To Setup Quotes API in Your PHP/JAVA Projects - FindIpInfo

Free Source Code - Codeintra
Quotes API Integration Guide

Welcome to the API Integration Guide! This document will help you seamlessly integrate our API into your website using PHP. Our API provides detailed information about IP addresses, including geographical location, time zone, currency, and more.

Step 1: Obtaining API Key To authenticate your requests and ensure security, you'll need to obtain an API key from our platform. Please follow these steps to generate your unique API key:

  • Visit our website at https://krishnaip.net
  • Sign up for an account or log in if you already have one. 
  • Navigate to the API section in your account settings. 
  • Generate an API key and copy it for future use.

Step 2: Making API Requests Now that you have your API key, you can start making API requests. Here's an example of how to make a request:

1. Add Retrofit and GSON dependencies:

Add the following dependencies to your build.gradle file:

dependencies {
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
}

2. Create a Quote interface:

Create a Quote class to represent the data structure of a quote returned by the API:

public class Quote {
    private String quote;
    private String author;
    private String category;

    public Quote(String quote, String author, String category) {
        this.quote = quote;
        this.author = author;
        this.category = category;
    }

    public String getQuote() {
        return quote;
    }

    public void setQuote(String quote) {
        this.quote = quote;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        this.category = category;
    }
}

3. Define the API interface:

Create an interface for your API service with a method to retrieve quotes:

public interface QuotesApi {
    @GET('/api/quotes/ApiKey')
    Call<QuotesResponse> getQuotes();
}

4. Define a QuotesResponse class:

This class represents the full response structure, including pagination information:

public class QuotesResponse {
    private String code;
    private String status;
    private String title;
    private List<Quote> quotes;
    private String nextPageUrl;
    private String prevPageUrl;

    public List<Quote> getQuotes() {
    return quotes;
    }

    public String getNextPageUrl() {
    return nextPageUrl;
    }

    public String getPrevPageUrl() {
    return prevPageUrl;
    }
}

5. Create Retrofit instance:

Create a Retrofit instance with the base URL and GSON converter:

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("https://krishnaip.net/")
        .addConverterFactory(GsonConverterFactory.create())
        .build();

6. Implement API call:

Create a class or method to perform the API call:

public class ApiManager {
    private QuotesApi api;

    public ApiManager() {
        api = retrofit.create(QuotesApi.class);
    }

    public void getQuotes(SuccessCallback<List<Quote>> successCallback,
                            ErrorCallback errorCallback) {
        Call<QuotesResponse> call = api.getQuotes();
        call.enqueue(new Callback<QuotesResponse>() {
            @Override
            public void onResponse(Call<QuotesResponse> call, Response<QuotesResponse> response) {
                if (response.isSuccessful()) {
                    QuotesResponse quotesResponse = response.body();
                    if (quotesResponse != null) {
                        successCallback.onSuccess(quotesResponse.getQuotes());
                    } else {
                        errorCallback.onError("Empty response body");
                    }
                } else {
                    errorCallback.onError("Error occurred: " + response.code());
                }
            }

            @Override
            public void onFailure(Call<QuotesResponse> call, Throwable t) {
                errorCallback.onError("API error: " + t.getMessage());
            }
        });
    }

    public interface SuccessCallback<T> {
        void onSuccess(T data);
    }

    public interface ErrorCallback {
        void onError(String message);
    }
}

7. Call the API and handle response:

In your activity or fragment, call the getQuotes method and handle the success and error callbacks:

ApiManager apiManager = new ApiManager();
apiManager.getQuotes(new ApiManager.SuccessCallback>() {
    @Override
    public void onSuccess(List quotes) {
        // Update your UI with the list of quotes
        recyclerView.setAdapter(new QuotesAdapter(quotes));
    }
}, new ApiManager.ErrorCallback() {
    @Override
    public void onError(String message) {
        // Show error message to the user
        Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
    }
});

8. Adapter for RecyclerView:

Create an adapter to display the quote data in a RecyclerView:

public class QuotesAdapter extends RecyclerView.Adapter<QuotesAdapter.QuoteViewHolder> {
    private List<Quote> quotes;

    public QuotesAdapter(List<Quote> quotes) {
        this.quotes = quotes;
    }

    @Override
    public QuoteViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.quote_item, parent, false);
        return new QuoteViewHolder(view);
    }

    @Override
    public void onBindViewHolder(QuoteViewHolder holder, int position) {
        Quote quote = quotes.get(position);
        holder.quoteText.setText(quote.getQuote());
        holder.authorText.setText(quote.getAuthor());
    }

    @Override
    public int getItemCount() {
        return quotes.size();
    }

    public class QuoteViewHolder extends RecyclerView.ViewHolder {

        TextView quoteText;
        TextView authorText;

        public QuoteViewHolder(View itemView) {
            super(itemView);
            quoteText = itemView.findViewById(R.id.quote_text);
            authorText = itemView.findViewById(R.id.author_text);
        }
    }
}

Explanation:

  • This adapter extends RecyclerView.Adapter and defines a QuoteViewHolder class.
  • The onCreateViewHolder method inflates the quote item layout for each ViewHolder.
  • The onBindViewHolder method binds the quote data (text and author) to the corresponding views in the ViewHolder.
  • The getItemCount method returns the number of quotes in the list.
  • The QuoteViewHolder class holds references to the TextViews displaying the quote and author details.

9. Create XML Layout For Adapter Class:

Create an adapter layout view quote_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="16dp">

    <TextView
        android:id="@+id/quote_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Quote Text"
        android:textSize="18sp"
        android:textColor="@android:color/black" />

    <TextView
        android:id="@+id/author_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Author Name"
        android:textSize="14sp"
        android:textColor="@android:color/gray"
        android:layout_marginTop="8dp" />
</LinearLayout>

Explanation:

  • The LinearLayout defines a vertical container for the quote and author.
  • The quote_text TextView displays the quote text with larger size and black color.
  • The author_text TextView displays the author name with smaller size and gray color.
  • The padding attribute adds space around the text views for better visual presentation.

Customization:

  • You can change the text sizes, colors, fonts, and layout attributes to match your app's design.
  • You can add additional elements like an image or a rating for each quote.
  • Remember to update the QuotesAdapter class with the actual IDs of your TextViews if you change them in the layout.

Step 3: Error Handling It's essential to handle any errors that may occur during API requests. Here's an example of how to handle errors using PHP:

The API response contains a 'status' field that indicates the result of the API request. Here are the possible status values and their meanings:

 

'success': This status indicates that the API request was successful, and the desired information can be extracted from the response.

 

'api_error': If the API key provided in the request is invalid, this status will be returned. Make sure you are using a valid and active API key obtained from our platform.

 

Here's an example of how you can handle these status responses in your code:

Modify api.getQuotes method:

public void getQuotes(SuccessCallback<List<Quote>> successCallback, ErrorCallback errorCallback) {
    Call<QuotesResponse> call = api.getQuotes();
    call.enqueue(new Callback<QuotesResponse>() {
        @Override
        public void onResponse(Call<QuotesResponse> call, Response<QuotesResponse> response) {
            QuotesResponse quotesResponse = response.body();
            if (quotesResponse != null) {
                if (quotesResponse.getStatus().equals("success")) {
                    successCallback.onSuccess(quotesResponse.getQuotes());
                } else {
                    errorCallback.onError("API error: " + quotesResponse.getStatus());
                }
            } else {
                errorCallback.onError("Empty response body");
            }
        }

        @Override
        public void onFailure(Call<QuotesResponse> call, Throwable t) {
            errorCallback.onError("Network error: " + t.getMessage());
        }
    });
}
API Parameters

API URL: The API URL is the endpoint you will be sending your requests to.

'ApiKey' (required): Your unique API key obtained from our platform. This key is necessary for authenticating your requests and ensuring the security of your integration.

Example API Request: An API request URL might look like this:

https://krishnaip.net/api/quotes/your-api-key-here
API Success Response

JSON Response Structure: The API response is formatted in JSON and contains various fields of information related to the provided IP address. Here is an example of the JSON response structure:

{
    "code": 200,
    "status": "success",
    "title": "Quotes From All Categories",
    "quotes": [
    {
        "quote": "If it is true that our species is alone in the universe, then I do have to say the universe aimed rather low and settled for very little.",
        "author": "George Carlin",
        "category": "Alone"
    },
    // ... more quotes
    ],
    "next_page_url": "https://krishnaip.net/api/quotes/ApiKey?page=3",
    "prev_page_url": "https://krishnaip.net/api/quotes/ApiKey?page=1"
}
Invalid API Key Response
{"status":"api_error","message":"Invalid API Key","code":400}
Response Parameters Description:

Key fields in the response:

  • code: Integer representing the HTTP status code.
  • status: String indicating success or error.
  • title: String representing the title of the response (e.g., "Quotes From All Categories").
  • quotes: Array of objects containing information about each quote:
    • quote: String containing the quote text.
    • author: String containing the author of the quote.
    • category: String representing the category of the quote.
  • next_page_url: Optional string containing the URL to retrieve the next page of quotes.
  • prev_page_url: Optional string containing the URL to retrieve the previous page of quotes.

Support: If you have any questions or encounter any issues while integrating our API, please don't hesitate to contact our support team. Get in touch via Live Support Chat