paint-brush
API for Beginners: Requests, Responses, Resources, and GET Explained with Codeby@utsavjaiswal
1,081 reads
1,081 reads

API for Beginners: Requests, Responses, Resources, and GET Explained with Code

by Utsav JaiswalOctober 27th, 2022
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Requesting and receiving data from internet sources is one of the basics of programming but isn’t taught by most ‘Learn to Code <Programming Language’ courses. API helps a program fetch information from various internet sources. API has 3 elements - Request, Response, and Resource - The data within the response (‘Guten Tag’) is the resource. API requests need to be structured in a very precise way and are performed by using the relevant API method in the request.

Company Mentioned

Mention Thumbnail
featured image - API for Beginners: Requests, Responses, Resources, and GET Explained with Code
Utsav Jaiswal HackerNoon profile picture


Requesting and receiving data from internet sources is one of the basics of programming but isn’t taught by most ‘Learn to Code <Programming Language>’ courses. For self-taught programmers, this is one of the skills that will get you moving further along your learning journey and make you better than 90% of the others.


What is an API?

Short for Application Programming Interface, API helps a program fetch information from various internet sources.


Let’s say you’re building a basic currency conversion program in python. It takes an input amount of currency X and converts it into currency Y


Sample Code for reference:


def currency_converter ():

    currency_a = input ("Enter the currency you want to convert: ")

    currency_b = input ("Enter the currency you want to convert to: ")

    amount = float (input ("Enter the amount you want to convert: "))

    exchange_rate = float (input ("Enter the exchange rate: "))

    print(f"{amount} {currency_a} is equal to \
        {amount * exchange_rate} {currency_b}")
    
currency_converter ()


This program in its current form is no more than a glorified calculator - not of much use as a program. This is where APIs come in!!


With a few lines of code, this program can be made so powerful that it does not need to ask for the exchange rate. Instead, with APIs, the code would be able to fetch the current exchange rate and provide it to the program.


Need to make a program to give the country code for an input country? There’s an API for that.


Inventory in your warehouse? Data in your spreadsheet? Payment confirmation? Email notification?


All done with APIs!


To put it simply, APIs enable communications between computing devices in a standardized manner.


For example, if you go to Germany and use an interpreter to help translate for you, the interpreter is the API.


Components of an API

An API has 3 elements - Request, Response, and Resource.


  • Request - You asking the interpreter to say ‘Good Day’ to a German is the request
  • Response - What the German said back is the response
  • Resource - The data within the response (‘Guten Tag’) is the resource


In our program above, let’s see what the API needs to do:


"""

Request -- Our program requests for the currency_a -> currency_b exchange rate

Response -- API endpoint reads our request, fetches that information, and responds back

Resource -- The exchange rate data sent back is the resource

"""


API Endpoint? What’s that?


As we know by now (as self-taught programmers) that computers need very precise inputs in a very precise manner. Any deviation or any expectation from the computer to ‘understand things as we do’ is just going to lead to chaos!


In that vein, we must understand that even API requests need to be structured in a very precise way.


This is what the general structure of an API looks like:


  • API Endpoint -- This is the URL that receives the Request.


  • Method -- This is the type of API request and is of several types such as:


    • GET -- indicates that the request is looking to fetch info from the server.

    • POST -- indicates that the request is looking to send some info to a server.

    • DELETE -- indicates that the request is looking to delete some info from the server.

    • PUT/PATCH -- indicates that the request is looking to update existing info on the server.


  • Header -- This provides some context about the Resource Requested.


  • Body -- This is the main part of the request that triggers the Response.


CRUD Responses

CRUD stands for Create, Read, Update, and Delete and is performed by using the relevant API method in the API Request:

API Method

Response

Description

GET

Read

fetches existing info from the server

POST

Create

adds info to the server

DELETE

Delete

deletes info on the server

PUT/PATCH

Update

updates info on the server


Fetching Realtime Currency Rates into our Program

Now we’re sufficiently ready to fetch the real-time currency rates into our sample program given earlier. We’ll be using the requests module for this exercise which you can get via pip3 install requests in your code editor’s (like VSCode) terminal.


APIs that provide data come in Free and Paid forms - depending on the ease of use. I found a free source ExchangeRateAPI and shall be using it because it does not force me to sign up as long as I’m just testing here.


API data usually comes in the form of a JSON (very similar to a dictionary in python) for easy interpretation by the programmers fetching that data. Here’s the code for fetching the current price of the US Dollar via the API.


import requests
url =  "https://open.er-api.com/v6/latest/USD"
r = requests.get(url)
data = r.json()
print (data)


Running this code will output the following:


{'result': 'success', 
'provider': 'https://www.exchangerate-api.com', 
'documentation': 'https://www.exchangerate-api.com/docs/free', 
'terms_of_use': 'https://www.exchangerate-api.com/terms', 
'time_last_update_unix': 1666828952, 
'time_last_update_utc': 'Thu, 27 Oct 2022 00:02:32 +0000', 
'time_next_update_unix': 1666916222, 
'time_next_update_utc': 'Fri, 28 Oct 2022 00:17:02 +0000', 
'time_eol_unix': 0, 
'base_code': 'USD', 
'rates': {'USD': 1, 'AED': 3.6725, 'AFN': 87.825832, 'ALL': 118.121569, 
'AMD': 400.945057, 'ANG': 1.79, 'AOA': 469.341287, 'ARS': 155.541325, 'AUD': 1.541873,
 'AWG': 1.79, 'AZN': 1.703727, 'BAM': 1.945846, 'BBD': 2, 'BDT': 101.652423, 
'BGN': 1.946569, 'BHD': 0.376, 'BIF': 2061.89311, 'BMD': 1, 'BND': 1.40599, 
'BOB': 6.931975, 'BRL': 5.314395, 'BSD': 1, 'BTN': 81.988812, 'BWP': 13.376498, 
'BYN': 2.887549, 'BZD': 2, 'CAD': 1.355432, 'CDF': 2080.191892, 'CHF': 0.986916, 
'CLP': 967.707002, 'CNY': 7.181598, 'COP': 4992.818412, 'CRC': 624.374829, 'CUP': 24, 
'CVE': 109.702113, 'CZK': 24.428037, 'DJF': 177.721, 'DKK': 7.422296, 'DOP': 53.948303,
 'DZD': 140.691654, 'EGP': 19.734057, 'ERN': 15, 'ETB': 53.10939, 'EUR': 0.994984, 
'FJD': 2.280573, 'FKP': 0.862476, 'FOK': 7.422296, 'GBP': 0.862495, 'GEL': 2.780813, 
'GGP': 0.862476, 'GHS': 14.477856, 'GIP': 0.862476, 'GMD': 60.196663, 
'GNF': 8658.722933, 'GTQ': 7.851475, 'GYD': 210.222337, 'HKD': 7.848858, 
'HNL': 24.756699, 'HRK': 7.496037, 'HTG': 127.760311, 'HUF': 407.402111, 
'IDR': 15518.182729, 'ILS': 3.502567, 'IMP': 0.862476, 'INR': 81.991335, 
'IQD': 1466.589463, 'IRR': 42121.422024, 'ISK': 142.934149, 'JEP': 0.862476, 
'JMD': 153.171604, 'JOD': 0.709, 'JPY': 146.478104, 'KES': 121.814832, 
'KGS': 83.278965, 'KHR': 4159.804229, 'KID': 1.541816, 'KMF': 489.456326, 
'KRW': 1414.443423, 'KWD': 0.29963, 'KYD': 0.833333, 'KZT': 470.670656, 
'LAK': 17297.850805, 'LBP': 1507.5, 'LKR': 362.205766, 'LRD': 154.022883, 
'LSL': 17.964161, 'LYD': 5.043916, 'MAD': 10.860577, 'MDL': 19.373927, 
'MGA': 4262.390442, 'MKD': 61.999441, 'MMK': 2425.598271, 'MNT': 3414.010756, 
'MOP': 8.084315, 'MRU': 38.145372, 'MUR': 43.95057, 'MVR': 15.474793, 
'MWK': 1033.698319, 'MXN': 19.911183, 'MYR': 4.709804, 'MZN': 64.481751, 
'NAD': 17.964161, 'NGN': 437.991325, 'NIO': 36.062907, 'NOK': 10.27411, 
'NPR': 131.1821, 'NZD': 1.717982, 'OMR': 0.384497, 'PAB': 1, 'PEN': 3.994793, 
'PGK': 3.535979, 'PHP': 58.319524, 'PKR': 220.984121, 'PLN': 4.728217, 
'PYG': 7249.701869, 'QAR': 3.64, 'RON': 4.844272, 'RSD': 116.906933, 
'RUB': 61.346183, 'RWF': 1075.383068, 'SAR': 3.75, 'SBD': 8.07199, 'SCR': 13.126076, 
'SDG': 572.688874, 'SEK': 10.875131, 'SGD': 1.405948, 'SHP': 0.862476, 
'SLE': 17.636956, 'SLL': 17636.95595, 'SOS': 571.245973, 'SRD': 29.467417, 
'SSP': 611.916602, 'STN': 24.374931, 'SYP': 2514.92413, 'SZL': 17.964161, 
'THB': 37.747911, 'TJS': 10.200292, 'TMT': 3.504191, 'TND': 3.085688, 
'TOP': 2.388017, 'TRY': 18.607129, 'TTD': 6.77608, 'TVD': 1.541816, 
'TWD': 32.049926, 'TZS': 2335.14976, 'UAH': 37.234725, 'UGX': 3826.845217, 
'UYU': 41.283595, 'UZS': 11139.838897, 'VES': 8.4508, 'VND': 24821.263771, 
'VUV': 122.039898, 'WST': 2.787278, 'XAF': 652.608434, 'XCD': 2.7, 'XDR': 0.774448, 
'XOF': 652.608434, 'XPF': 118.722827, 'YER': 251.106608, 'ZAR': 17.964381, 
'ZMW': 16.127703, 'ZWL': 644.87339}}


Looking at this JSON (Imma call it a dictionary from hereon for pythonic reasons), we see that the currency rates against that of the USD as base currency are given in the internal dictionary which can be accessed with the rates key.


The actual conversion rate to a particular currency can be accessed by using the desired currency’s 3-letter currency code.


For example, to get the conversion rate to INR (Indian Rupee), I will first need to use the rates key and then the INR key within the rates key.


Case-sensitivity is important in most APIs so we’ll need to plan for that in our code as well.


The code to get the USD to INR conversion rate, the code in python would look like this -


inr_rate = data['rates'].get('INR', 'Not Found')


Let’s now update our original code to become less of a calculator and more of a computer:


import requests

def currency_converter ():
    currency_a = input ("Enter the currency you want to convert: ")
    currency_a = currency_a.upper() 
    #accepts user input for base currency name and converts it to uppercase
    
    currency_b = input ("Enter the currency you want to convert to: ")
    currency_b = currency_b.upper() 
    #accepts user input for final currency name and converts it to uppercase
    
    currency_converter_api = "https://open.er-api.com/v6/latest/" + currency_a
    #makes currency_a the base currency
    
    api_response = requests.get(currency_converter_api)
    #fetches the api response - the R from CRUD
    
    api_response_json = api_response.json()
    #Converts the response object into a JSON object
    
    amount_to_convert = float (input (f"Enter the amount of {currency_a} \
      you want to convert to {currency_b}: "))
    #accepts user input for the amount to convert as a float
    
    try:
        exchange_rate = api_response_json['rates'].get(currency_b, \
          'Currency Not Supported by API')

        if exchange_rate == 'Currency Not Supported by API':

            print ("Final Currency Not Supported by API")

        else:

            converted_amount = amount_to_convert * exchange_rate

            print (f"{amount_to_convert} {currency_a} is \
              equal to {converted_amount} {currency_b}")
    
    except KeyError:
        print ("Base Currency Not Supported by API")
    # for catching errors is the base currency name is not supported by the API
    
currency_converter ()


There you go - now it does a little better:


Converting 5000 INR to EUR (successful conversion calculation):


"""
Enter the currency you want to convert: inr
Enter the currency you want to convert to: eur
Enter the amount of INR you want to convert to EUR: 5000
5000.0 INR is equal to 60.72 EUR
"""


Converting unsupported currency (error-handling):


"""
Enter the currency you want to convert: utsav
Enter the currency you want to convert to: inr
Enter the amount of UTSAV you want to convert to INR: 45
Base Currency Not Supported by API
"""


Converting TO Unsupported currency (error-handling):


"""
Enter the currency you want to convert: inr
Enter the currency you want to convert to: utsav
Enter the amount of INR you want to convert to UTSAV: 89
Final Currency Not Supported by API
"""


Some Final Notes: