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:
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. Include Libraries:
<?php
// Include necessary libraries
require 'vendor/autoload.php'; // Assuming Composer for libraries
use GuzzleHttp\Client;
2. Define API Configuration:
// API base URL with API key included
$apiUrl = 'https://krishnaip.net/api/quotes/ApiKey'; // Replace with your actual API key
// No need for separate headers array
$headers = [];
3. Implement a Quotes Response Class:
class QuotesResponse
{
public $code;
public $status;
public $title;
public $quotes;
public $nextPageUrl;
public $prevPageUrl;
public function __construct($data)
{
$this->code = $data['code'];
$this->status = $data['status'];
$this->title = $data['title'];
$this->quotes = array_map(function ($quote) {
return new Quote($quote);
}, $data['quotes']);
$this->nextPageUrl = $data['next_page_url'];
$this->prevPageUrl = $data['prev_page_url'];
}
}
class Quote
{
public $quote;
public $author;
public $category;
public function __construct($data)
{
$this->quote = $data['quote'];
$this->author = $data['author'];
$this->category = $data['category'];
}
}
4. Create a Function to Fetch Quotes:
function fetchQuotes($page = 1)
{
global $apiUrl, $headers;
$url = $apiUrl . '?page=' . $page;
$client = new Client();
$response = $client->get($url, ['headers' => $headers]);
$data = json_decode($response->getBody()->getContents(), true);
return new QuotesResponse($data);
}
5. Usage Example:
// Fetch quotes from the first page
$quotesResponse = fetchQuotes();
// Check for successful response
if ($quotesResponse->code === 200 && $quotesResponse->status === 'success') {
// Display quotes
foreach ($quotesResponse->quotes as $quote) {
echo $quote->quote . " - " . $quote->author . " (" . $quote->category . ")" . PHP_EOL;
}
// Check for next page
if ($quotesResponse->nextPageUrl) {
// Fetch and display quotes from the next page
$nextPageResponse = fetchQuotes($page + 1);
// ... display or handle quotes as needed
}
} else {
echo "Error: " . $quotesResponse->message;
}
Explanation:
QuotesResponse
and Quote
classes to structure the
API response data.fetchQuotes
function retrieves quotes for a specific page and returns a
QuotesResponse
object.
Remember to:
ApiKey
with your actual API key.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:
RecyclerView.Adapter
and defines a
QuoteViewHolder
class.
onCreateViewHolder
method inflates the quote item layout for each
ViewHolder.onBindViewHolder
method binds the quote data (text and author) to the
corresponding views in the ViewHolder.getItemCount
method returns the number of quotes in the list.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:
LinearLayout
defines a vertical container for the quote and author.
quote_text
TextView displays the quote text with larger size and black
color.author_text
TextView displays the author name with smaller size and
gray color.Customization:
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:
API Issues:
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 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
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"
}
{"status":"api_error","message":"Invalid API Key","code":400}
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