Skip to main content

Command Palette

Search for a command to run...

Automating Tour Package Data Management via APIs

Updated
5 min read
J

Python Django Developer | Django Rest Framework, AWS | Melbourne-based | Available for Immediate Start

APIs

1. Google SpreadSheet API

Google Spreadsheet API

Google SpreadSheet with Python

We can utilize two different REST APIs to interact with Google Sheets data:

get

GET /v4/spreadsheets/{spreadsheetId}
return spreadsheet of given ID

post

POST /v4/spreadsheets/`{spreadsheetId}/values/{range}:append
append value in spreadsheet

  • Format: https://docs.google.com/spreadsheets/d/ SPREADSHEET_ID /edit

Code Example

import os.path

from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

# If modifying these scopes, delete the file token.json.
SCOPES = ["https://www.googleapis.com/auth/spreadsheets"]

# The ID and range of a sample spreadsheet.
SAMPLE_SPREADSHEET_ID = "***"
SAMPLE_RANGE_NAME = "시트1!A2:E2"


def main():
  """Shows basic usage of the Sheets API.
  Prints values from a sample spreadsheet.
  """
  creds = None
  # The file token.json stores the user's access and refresh tokens, and is
  # created automatically when the authorization flow completes for the first
  # time.
  if os.path.exists("token.json"):
    creds = Credentials.from_authorized_user_file("token.json", SCOPES)
  # If there are no (valid) credentials available, let the user log in.
  if not creds or not creds.valid:
    if creds and creds.expired and creds.refresh_token:
      creds.refresh(Request())
    else:
      flow = InstalledAppFlow.from_client_secrets_file(
          "credentials.json", SCOPES
      )
      creds = flow.run_local_server(port=0)
    # Save the credentials for the next run
    with open("token.json", "w") as token:
      token.write(creds.to_json())

  try:
    service = build("sheets", "v4", credentials=creds)

    # Call the Sheets API
    sheet = service.spreadsheets()
    result = (
        sheet.values()
        .get(spreadsheetId=SAMPLE_SPREADSHEET_ID, range=SAMPLE_RANGE_NAME)
        .execute()
    )
    values = result.get("values", [])

    if not values:
      print("No data found.")
      return

    print("Name, Major:")
    for row in values:
      print("row: ", row)

      # Print columns A and E, which correspond to indices 0 and 4.
      print(f"{row[0]}, {row[2]}")
  except HttpError as err:
    print(err)


if __name__ == "__main__":
  main()

2. Google Calendar API

Google Workspace Test API

Google Calendar with Python

Calendar APIs

  1. In Google Cloud Console, Google Calendar API

  2. Create Branding

  3. Install python library

    python3 -m pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
    
  4. Install credentials.json file from Google API Console

  5. OAuth

  6. Create quickstart.py

    import datetime
    import os.path
    
    from google.auth.transport.requests import Request
    from google.oauth2.credentials import Credentials
    from google_auth_oauthlib.flow import InstalledAppFlow
    from googleapiclient.discovery import build
    from googleapiclient.errors import HttpError
    
    # If modifying these scopes, delete the file token.json.
    SCOPES = ["https://www.googleapis.com/auth/calendar"]
    
    
    def main():
      """Shows basic usage of the Google Calendar API.
      Prints the start and name of the next 10 events on the user's calendar.
      """
      creds = None
      # The file token.json stores the user's access and refresh tokens, and is
      # created automatically when the authorization flow completes for the first
      # time.
      if os.path.exists("token.json"):
        creds = Credentials.from_authorized_user_file("token.json", SCOPES)
      # If there are no (valid) credentials available, let the user log in.
      if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
          creds.refresh(Request())
        else:
          flow = InstalledAppFlow.from_client_secrets_file(
              "credentials.json", SCOPES
          )
          creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open("token.json", "w") as token:
          token.write(creds.to_json())
    
      try:
        service = build("calendar", "v3", credentials=creds)
    
        # Call the Calendar API
        now = datetime.datetime.now(tz=datetime.timezone.utc).isoformat()
        print("Getting the upcoming 10 events")
        events_result = (
            service.events()
            .list(
                calendarId="primary",
                timeMin=now,
                maxResults=10,
                singleEvents=True,
                orderBy="startTime",
            )
            .execute()
        )
        events = events_result.get("items", [])
    
        event = {
      'summary': 'Google I/O 2026',
      'location': '800 Howard St., San Francisco, CA 94103',
      'description': 'A chance to hear more about Google\'s developer products.',
      'start': {
        'dateTime': '2026-04-20T09:00:00-07:00',
        'timeZone': 'America/Los_Angeles',
      },
      'end': {
        'dateTime': '2026-04-20T09:00:00-07:00',
        'timeZone': 'America/Los_Angeles',
      },
      'recurrence': [
        'RRULE:FREQ=DAILY;COUNT=2'
      ],
      'attendees': [
        {'email': 'lpage@example.com'},
        {'email': 'sbrin@example.com'},
      ],
      'reminders': {
        'useDefault': False,
        'overrides': [
          {'method': 'email', 'minutes': 24 * 60},
          {'method': 'popup', 'minutes': 10},
        ],
      },
    }
    
        event = service.events().insert(calendarId='primary', body=event).execute()
        print('Event created: %s' % (event.get('htmlLink')))
    
    
        if not events:
          print("No upcoming events found.")
          return
        
        # Prints the start and name of the next 10 events
        for event in events:
          start = event["start"].get("dateTime", event["start"].get("date"))
          print(start, event["summary"])
    
    
      except HttpError as error:
        print(f"An error occurred: {error}")
    
    
    if __name__ == "__main__":
      main()
    
  7. Insufficient Permission Errors

Insufficient Error

3. My Realtrip API

My Realtrip API

POST /v1/products/tna/detail

Path Parameters

gid (required) string

product ID

ex) 5869248

Request example

cURL

curl --request POST \
  --url https://partner-ext-api.myrealtrip.com/v1/products/tna/detail \
  --header 'Authorization: Bearer YOUR_API_KEY' \
  --header 'Content-Type: application/json' \
  --data '{"gid":"5869248"}'

Response example

  • gid*· string

Product ID

  • description· string

Product introduction (HTML included)

  • excluded· array

Excluded details list

  • included· array

Included details list

  • itineraries· array

Itineraries information

  • itineraries[].description· string

Itineraries description

  • itineraries[].title· string

Itineraries title

  • reviewCount· integer

Review counts

  • reviewScore· number

Review score (1.0~5.0)

  • title· string

Product title

Response Example

{
  "data": {
    "gid": "5869248",
    "title": "오사카 난카이 라피트 편도 E-티켓 (간사이 공항 ↔ 난카이 난바역)",
    "description": "오사카 난카이 라피트 편도 E-티켓으로 간사이 공항에서 난바역까지 빠르고 편리하게 이동하세요.",
    "reviewScore": 4.83,
    "reviewCount": 1250,
    "included": [
      "난카이 라피트 편도 E-티켓"
    ],
    "excluded": [
      "개인 경비"
    ],
    "itineraries": []
  },
  "meta": {},
  "result": {
    "status": 200,
    "message": "SUCCESS",
    "code": "success"
  }
}

Error Code Guide

Code Example

import requests

url = "https://partner-ext-api.myrealtrip.com/v1/search"
headers = {
    "Authorization": "Bearer YOUR_API_KEY",
    "Content-Type": "application/json"
}
params = {
    "gid": "5869248",
}

response = requests.get(url, headers=headers, params=params)
data = response.json()
print(data)

Steps

  1. Install Python IDLE.

  2. Log in to the Myrealtrip Partnership portal.

  3. Generate a new API Key.

  4. Define the request and response parameters.

  5. Execute and test the code.