Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
305 changes: 305 additions & 0 deletions .ipynb_checkpoints/working_with_APIS-checkpoint.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,305 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "3be4f6cf",
"metadata": {},
"source": [
"# Lab | Working with APIs"
]
},
{
"cell_type": "code",
"execution_count": 30,
"id": "e39d3345",
"metadata": {},
"outputs": [],
"source": [
"#Instructions\n",
"#Create a function that returns a Pandas dataframe with the price, names of origin and arrival airports and the name of the company. \n",
"#Do it for all the flights between two dates."
]
},
{
"cell_type": "code",
"execution_count": 31,
"id": "e8e76a73",
"metadata": {},
"outputs": [],
"source": [
"import requests\n",
"import pandas as pd\n",
"import json\n",
"import datetime"
]
},
{
"cell_type": "code",
"execution_count": 32,
"id": "35e16bfd",
"metadata": {},
"outputs": [],
"source": [
"URL = \"https://partners.api.skyscanner.net/apiservices/v3/flights/indicative/search\"\n",
"HEADERS = {\"x-api-key\": \"prtl6749387986743898559646983194\"}"
]
},
{
"cell_type": "code",
"execution_count": 33,
"id": "9b3b38ae",
"metadata": {},
"outputs": [],
"source": [
"def flatten_dict(dd, separator='_', prefix=''):\n",
" return {f\"{prefix}{separator}{k}\" if prefix else k: v\n",
" for kk, vv in dd.items()\n",
" for k, v in (flatten_dict(vv, separator, kk).items() if isinstance(vv, dict) else {kk: vv}.items())}"
]
},
{
"cell_type": "code",
"execution_count": 34,
"id": "596cf4f3",
"metadata": {},
"outputs": [],
"source": [
"def flight_finder(start_date, end_date, origin, destination):\n",
" # Create list with [start_date, start_date+1, ...., end_date]\n",
" start_year = start_date // 10000\n",
" start_month = (start_date // 100) % 100\n",
" start_day = start_date % 100\n",
" start_datetime = datetime.datetime(start_year, start_month, start_day)\n",
" \n",
" end_year = end_date // 10000\n",
" end_month = (end_date // 100) % 100\n",
" end_day = end_date % 100\n",
" end_datetime = datetime.datetime(end_year, end_month, end_day)\n",
"\n",
" date_range = []\n",
" current_date = start_datetime\n",
" while current_date <= end_datetime:\n",
" date_range.append(current_date)\n",
" current_date += datetime.timedelta(days=1)\n",
" \n",
" quotes = [] \n",
" for date in date_range: \n",
"\n",
"\n",
" payload = { \"query\": {\n",
" \"market\": \"UK\",\n",
" \"locale\": \"en-GB\",\n",
" \"currency\": \"EUR\",\n",
" \"queryLegs\": [\n",
" {\n",
" \"originPlace\": { \"queryPlace\": { \"iata\": origin } },\n",
" \"destinationPlace\": { \"queryPlace\": { \"iata\": destination } },\n",
" \"fixedDate\": {\n",
" \"year\": date.year,\n",
" \"month\": date.month,\n",
" \"day\": date.day\n",
" }\n",
" }\n",
" ]\n",
" } }\n",
"\n",
" response = requests.post(URL, json=payload, headers=HEADERS)\n",
" output = response.json()\n",
" results = output['content']['results']\n",
" quotes.append(results['quotes'])\n",
"\n",
" dataframes = []\n",
"\n",
" for dictionary in quotes:\n",
" flattened_results = [flatten_dict(dictionary) for dictionary in dictionary.values()]\n",
" df = pd.DataFrame.from_records(flattened_results)\n",
" df.columns = [col.split(\".\")[-1] for col in df.columns]\n",
" dataframes.append(df)\n",
"\n",
" combined_df = pd.concat(dataframes, ignore_index=True)\n",
" \n",
" return combined_df"
]
},
{
"cell_type": "code",
"execution_count": 37,
"id": "e0298423",
"metadata": {},
"outputs": [],
"source": [
"df = flight_finder(20230501, 20230502, 'TFN', 'LIS')"
]
},
{
"cell_type": "code",
"execution_count": 38,
"id": "f4dac065",
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<style scoped>\n",
" .dataframe tbody tr th:only-of-type {\n",
" vertical-align: middle;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: right;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
"Empty DataFrame\n",
"Columns: []\n",
"Index: []"
]
},
"execution_count": 38,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"df.head(10)"
]
},
{
"cell_type": "code",
"execution_count": 41,
"id": "17261d44",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[datetime.datetime(2023, 1, 1, 0, 0),\n",
" datetime.datetime(2023, 1, 2, 0, 0),\n",
" datetime.datetime(2023, 1, 3, 0, 0),\n",
" datetime.datetime(2023, 1, 4, 0, 0),\n",
" datetime.datetime(2023, 1, 5, 0, 0),\n",
" datetime.datetime(2023, 1, 6, 0, 0),\n",
" datetime.datetime(2023, 1, 7, 0, 0),\n",
" datetime.datetime(2023, 1, 8, 0, 0),\n",
" datetime.datetime(2023, 1, 9, 0, 0),\n",
" datetime.datetime(2023, 1, 10, 0, 0)]"
]
},
"execution_count": 41,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Testing code\n",
"start_date = 20230101\n",
"end_date = 20230110\n",
"start_year = start_date // 10000\n",
"start_month = (start_date // 100) % 100\n",
"start_day = start_date % 100\n",
"start_datetime = datetime.datetime(start_year, start_month, start_day)\n",
"\n",
"end_year = end_date // 10000\n",
"end_month = (end_date // 100) % 100\n",
"end_day = end_date % 100\n",
"end_datetime = datetime.datetime(end_year, end_month, end_day)\n",
"\n",
"date_range = []\n",
"current_date = start_datetime\n",
"while current_date <= end_datetime:\n",
" date_range.append(current_date)\n",
" current_date += datetime.timedelta(days=1)\n",
"date_range"
]
},
{
"cell_type": "code",
"execution_count": 67,
"id": "523811a9",
"metadata": {},
"outputs": [],
"source": [
"quotes = [] \n",
"for date in date_range: \n",
" url = \"https://partners.api.skyscanner.net/apiservices/v3/flights/indicative/search\"\n",
"\n",
" payload = { \"query\": {\n",
" \"market\": \"UK\",\n",
" \"locale\": \"en-GB\",\n",
" \"currency\": \"EUR\",\n",
" \"queryLegs\": [\n",
" {\n",
" \"originPlace\": { \"queryPlace\": { \"iata\": 'LIS' } },\n",
" \"destinationPlace\": { \"queryPlace\": { \"iata\": 'MAD' } },\n",
" \"fixedDate\": {\n",
" \"year\": date.year,\n",
" \"month\": date.month,\n",
" \"day\": date.day\n",
" }\n",
" }\n",
" ]\n",
" } }\n",
" headers = {\n",
" \"x-api-key\": \"prtl6749387986743898559646983194\"\n",
" }\n",
" response = requests.post(url, json=payload, headers=headers)\n",
" output = response.json()\n",
" results = output['content']['results']\n",
" quotes.append(results['quotes'])\n",
"\n",
"print(response)\n",
"output\n",
" \n",
"# dataframes = []\n",
"\n",
"# for dictionary in quotes:\n",
"# flattened_results = [flatten_dict(dictionary) for dictionary in dictionary.values()]\n",
"# df = pd.DataFrame.from_records(flattened_results)\n",
"# df.columns = [col.split(\".\")[-1] for col in df.columns]\n",
"# dataframes.append(df)\n",
"\n",
"# combined_df = pd.concat(dataframes, ignore_index=True)\n",
"\n",
"\n",
"# combined_df.head()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.13"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
Loading