import pandas as pd
import requests
import json
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
# Make the get request - it appears fruityvice is temporarily out of order
= requests.get("https://fruityvice.com/api/fruit/all")
data
# The text data type returned is json so use json.loads to load it
= json.loads(data.text)
results
# View the first two elements
2] results[:
Convert json to DF
= pd.DataFrame(results)
df3 3) df3.head(
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
= pd.json_normalize((results))
df3 5) df3.head(
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
= df3[df3["name"] == "Cherry"]
cherry cherry
- Extract the family using the label method. Since we know we only have one row we can use [ :, ccc]
'family']] cherry.loc[:,[
- Let’s extract genus using the location method iloc
0]['genus'] cherry.iloc[
Calories in Banana
= df3[df3["name"] == "Banana"]
banana 'nutritions.calories']] banana.loc[:,[