Send Get Request

API Fruityvice - JSON to df

Currently the webservice consists of two functions:

  • Receiving data for a specific fruit or all fruit, and
  • A function to add your own data.
  • An example of what the response body would look like

  • To receive the shown data, you have to make a HTTP GET call on the resource /api/fruit/{ID} or /api/fruit/{name} of this website’s IP.
  • To add data, make a HTTP PUT call on the resource /api/fruit with the data of a fruit in JSON format in the request body.

Case Study

Make an HTTP get request call

Data returned will be in json format, so convert the response data to pandas df

Normalize/flatten the results

Find out how many calories in a banana

Setup

import pandas as pd
import requests
import json
# Make the get request - it appears fruityvice is temporarily out of order
data = requests.get("https://fruityvice.com/api/fruit/all")

# The text data type returned is json so use json.loads to load it
results = json.loads(data.text)

# View the first two elements
results[:2]

Convert json to DF

df3 = pd.DataFrame(results)
df3.head(3)

Normalize/Flatten DF

  • As you can see above, the nutritions column contains multiple subcolumns
  • We need to flatten or normalize it
# Flaten or Normalize the df
df3 = pd.json_normalize((results))
df3.head(5)

Extract Information

Genus & Family of a Cherry

  • Filter out the Cherry row
# create a cherry var
#cherry = df3["name"] == "Cherry" this gives us a column of False & True

# this will give us the row from the df that has a value of True
cherry = df3[df3["name"] == "Cherry"]
cherry

  • Extract the family using the label method. Since we know we only have one row we can use [ :, ccc]
cherry.loc[:,['family']]

  • Let’s extract genus using the location method iloc
cherry.iloc[0]['genus']

Calories in Banana

banana = df3[df3["name"] == "Banana"]
banana.loc[:,['nutritions.calories']]