Frankfurt School Logo

Python

Application Programming Interfaces (APIs)

Real-world programs combine services

How an API request works

sequenceDiagram
  participant P as Python program
  participant F as Frankfurter service
  P->>F: HTTPS GET request with endpoint and parameters
  F->>F: Look up requested exchange rates
  F-->>P: HTTP status and JSON response
  P->>P: Decode JSON and use returned data

  • The endpoint identifies the requested resource; parameters specify what data to return.
  • The status code reports whether the request succeeded.
  • The response body contains data; r.json() converts JSON into Python values.

Frankfurter — retrieve exchange rates

The public Frankfurter API requires no API key. Its rates are daily reference rates, not live trading prices.

import requests

url = "https://api.frankfurter.dev/v2/rates?from=2025-01-01&to=2025-01-31&base=EUR&quotes=USD"

r = requests.get(url)
r.raise_for_status()
data = r.json()
data[:2]

requests.get(url) sends the request; raise_for_status() checks for an HTTP error; r.json() decodes the response.

Task: adapt the request

  • Change the quote currency from USD to GBP and rerun the request.
  • Convert the returned data to a DataFrame and plot the rate.

OpenAI API — Using AI services in an application

from openai import OpenAI

client = OpenAI()

conversation = """Customer: I'd like to order 20 office chairs and 5 desks.
Sales: Should we deliver everything to Frankfurt?
Customer: Yes, please. Actually, make that 25 chairs.
Sales: Delivery next Friday would be possible.
Customer: Perfect. But we only need 3 desks."""

response = client.responses.create(
    model="gpt-6-luna",
    input="Extract the final order as JSON:\n" + conversation
)

print(response.output_text)

The openai Python library wraps the requests inside convenient functions.

API key setup

Before running the example, set the OPENAI_API_KEY environment variable in your terminal:

export OPENAI_API_KEY="your-api-key"

Outlook: programming with and without AI

Discussion — AI and learning to program

  • Have you used AI to learn Python or solve programming problems? What worked well?
  • When would conventional Python be preferable to an LLM service?
  • How would you check AI-generated code, including cases beyond the example input?
  • Have you used AI outside of the Web interface?

Python syntax – Rapid questions

Could we briefly review some key syntax patterns?
I often know which function to use but struggle to write it correctly,
and others may face similar difficulties.

How to play

For each example, be ready to predict the result, explain the syntax, or identify and correct an error. Try to explain the reusable pattern, not just remember one statement.

Case 1

sales.groupby("region")("turnover").sum()
  • Check and correct the syntax
  • What steps would be executed by the statement?

Solution

sales.groupby("region")["turnover"].sum()

Round brackets call groupby() and provide the grouping column. Square brackets select the turnover column.

Case 2

list(range(5))
list(range(1, 5))
list(range(1, 5, 2))
  • Which numbers does each expression generate?
  • What do the start, stop, and step values mean?
  • Is the stop value included?
  • How would you generate 10, 20, 30, 40, 50?

Solution

  • range(5) generates 0, 1, 2, 3, 4.
  • range(1, 5) generates 1, 2, 3, 4.
  • range(1, 5, 2) generates 1, 3.
  • The stop value is excluded. Use range(10, 51, 10) to generate 10, 20, 30, 40, 50.

Case 3

Consider each print() statement separately:

turnover = 1500

print("Turnover:", turnover)
print("Turnover: " + turnover)
print("Turnover: " + str(turnover))
  • Which statements work?
  • Which working statements produce the same output?
  • What is the difference between , and + here?

Solution

  • The first and third statements work; both display Turnover: 1500.
  • A comma passes separate values to print(), which inserts a space between them.
  • + combines strings. The second statement raises a TypeError because turnover is a number; convert it with str() first.

Case 4

Assume sales has the default integer index starting at zero:

sales.iloc[1:4]
sales.loc[1:4]
  • Which rows are selected by each expression?
  • Is the upper limit included?
  • What is the difference between iloc and loc?

Solution

  • iloc[1:4] selects positions 1, 2, and 3. Its stop position is excluded.
  • loc[1:4] selects labels 1, 2, 3, and 4. Its stop label is included.
  • iloc selects by position; loc selects by label.

Case 5

Consider each statement separately:

sales.plot(x="date", y="turnover")
sales.plot(x="date", y="turnover", kind="line")
sales.plot(x="date", y="turnover", kind="bar")
sales.plot(x="date", y="turnover", kind=bar)
  • Which statements work?
  • Do any of these statements produce the same plot?

Solution

  • The first three statements work. The fourth raises a NameError if bar has not been defined.
  • The first two make a line plot: line is the default kind.
  • kind is optional. "bar" is a string naming the plot type; without quotes, Python looks for a variable named bar.

Case 6

Assume the DataFrame has columns named region and turnover. Consider each statement separately:

sales.sort_values(by="region")
sales.sort_values(by="region", ascending="turnover")
sales.sort_values(by="region, turnover")
sales.sort_values(by=["region", "turnover"])
  • Which statements work as intended?
  • Why is a list needed to sort by multiple columns?
  • What is the difference between the parameter statements?

Solution

  • The first sorts by region; the fourth sorts by region, then by turnover.
  • The second passes a column name to ascending, which expects a Boolean, and raises a ValueError.
  • The third passes one string, so pandas looks for a single column named region, turnover and raises a KeyError if that column does not exist.
  • A comma inside a string is just text. A list contains two separate column names.

Case 7

turnover = 1500

if turnover > 1000:
    break
  • Is this valid Python code?

Solution

  • This raises a SyntaxError: break can only be used inside a for or while loop.
  • An if statement chooses whether to run a block; it does not create a loop.
  • Inside a loop, break terminates the innermost enclosing loop.

Case 8

x = 5

if x = 5:
    print("Five")
  • Is this valid Python code?
  • How would you correct the condition?

Solution

This raises a SyntaxError. A single = assigns a value; == compares values. Write:

if x == 5:
    print("Five")

Case 9

turnover = [1500, 2000, 1800, 2500]
total = sum(Turnover)
print(total)
  • What is the intended result?
  • Does the program work as written?
  • How would you correct it?

Solution

Python distinguishes uppercase and lowercase letters. Turnover is undefined, so the code raises a NameError. Use total = sum(turnover); the result is 7800.

Case 10

result = calculate_total(100, 20)

def calculate_total(price, quantity):
    return price * quantity

print(result)
  • Is this valid Python code?
  • How would you correct the program?

Solution

The call happens before the function has been defined, so this raises a NameError in a fresh program. Define the function first, then call it:

def calculate_total(price, quantity):
    return price * quantity

result = calculate_total(100, 20)
print(result)

The program displays 2000.

Case 11

def get_price():
    return 100

price_with_vat = get_price * 1.19
print(price_with_vat)
  • Does this program work as written?
  • What does get_price refer to?
  • How would you calculate the returned price with 19% VAT?

Solution

get_price refers to the function itself. Because it is missing round brackets, the function is not called, and multiplying it by 1.19 raises a TypeError. Call it to retrieve the price, then add 19% VAT:

price_with_vat = get_price() * 1.19
print(price_with_vat)

This displays 119.0.

Case 12

for x in range(5):
    if x == 2:
        continue
        print("Skipping")
    print(x)
  • What is printed?

Solution

The numbers 0, 1, 3, and 4 are printed. When x is 2, continue moves directly to the next iteration, so "Skipping" is never printed. The unreachable statement is valid syntax, not a syntax error.

Case 13

def calculate_total(price, quantity):
    print(price * quantity)

total = calculate_total(10, 5)
print(total)
  • What is printed?

Solution

The function prints 50, then print(total) displays None. The function prints the product but does not return it, so total receives Python’s default return value, None. Replacing the function’s print() with return would make total equal 50.

Case 14

Assess each statement independently:

products = ["Laptop", "Tablet", "Phone"]

print(products[0])
print(products[3])
print(products[-1])
print(products(1))
  • Which statements work?
  • How does Python count list positions?
  • What does a negative index mean?
  • Why are round brackets inappropriate for the last statement?

Solution

  • products[0] displays Laptop.
  • products[3] raises an IndexError: the last position is 2.
  • products[-1] displays Phone, the last item.
  • products(1) raises a TypeError: square brackets select an item; round brackets call a function.

Case 15

Do not run this loop as written. First find the problem.

x = 0
while x < 5:
    print(x)
  • Does this loop terminate?
  • What statement is missing?
  • Why would a for loop over a range not need this update?

Solution

The loop does not terminate because x stays at 0. Add an update inside the loop:

x = 0
while x < 5:
    print(x)
    x = x + 1

A for loop moves to the next value in its sequence automatically.

Case 16

sales.sort_values(by="turnover")
print(sales)
  • Is sales now sorted?
  • What happens to the result of sort_values()?
  • How would you retain the sorted DataFrame?

Solution

By default, sort_values() returns a new sorted DataFrame; it does not change sales in place. The first statement discards that returned DataFrame. Assign it to keep the result:

sales = sales.sort_values(by="turnover")

Diagnose the kind of mistake

  • Syntax error: Python cannot interpret the code, for example if x = 5: or break outside a loop.
  • Runtime error: the code is understood, but execution fails, for example an undefined name or an out-of-range list index.
  • Logic error: the code runs but does not behave as intended, for example a condition that is always true or a loop that never updates its counter.
  • Correct code: the program behaves as intended for the task.

Exam reminder

  • Use standard Python functions and syntax covered in class.
  • For Pandas questions in the interactive console, a bare expression displays its result; an assignment does not.
  • Check whether code both runs and produces the result the task asks for.

Open questions and feedback

Open questions

What would you still like to clarify before the exam?

  • Is there a syntax pattern you would like to review once more?
  • Do you have a question about APIs, programming, or using AI to support your work?

Please provide feedback

Please take 1–2 minutes to reflect on the course.

Complete the short feedback survey

All the best for your exams and the holidays!

If you are interested in theses or would like to discuss programming and analytics topics, I’d be happy to reconnect.