PYTHON · LANGUAGE & SYNTAX

17 · API Requests

APIs allow different systems to exchange data.

Simple idea

Python File ↓ import ↓ Use Code From Another Module

1. import

import loads a module.

Syntax

import module_name

Example

import math

Use it

result = math.sqrt(16)

print(result)

Output

4.0

2. module.function

After importing a module, access its functions with:

module.function()

Example

import random

number = random.randint(1, 10)

3. from ... import ...

Imports a specific item from a module.

Syntax

from module_name import item_name

Example

from math import sqrt

result = sqrt(16)

Now you can use sqrt() directly.

4. Import Multiple Items

from math import sqrt, ceil, floor

Then:

sqrt(16)
ceil(4.2)
floor(4.8)

5. as

as gives an imported module or item a shorter name.

import pandas as pd

Then:

df = pd.DataFrame()

Another example:

import numpy as np

6. Common Alias Examples

pandas      → pd
numpy       → np
matplotlib.pyplot → plt

Aliases are not mandatory.

7. Import Your Own Python File

project/
├── main.py
└── calculator.py

calculator.py

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

main.py

from calculator import calculate_total

total = calculate_total(8500, 10)

print(total)

Output

85000

8. import Entire Local Module

calculator.py

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

main.py

import calculator

total = calculator.calculate_total(8500, 10)

9. __name__

Python files have a built-in variable called:

__name__

A common pattern is:

if __name__ == "__main__":
    main()

Example

def main():
    print("Program started")

if __name__ == "__main__":
    main()

This means: Run main() when this file is executed directly.

10. Third-Party Packages

Some modules are not included with Python. They must be installed first.

pip install requests

Then:

import requests

Examples of third-party packages:

  • requests
  • pandas
  • numpy
  • fastapi

11. Standard Library vs Third-Party Package

Standard Library

Included with Python

os
json
datetime
pathlib
csv
math

Third-party

Installed separately

requests
pandas
numpy
fastapi

12. Import Error

import something_missing

May cause:

ModuleNotFoundError

Common reasons:

  • package is not installed
  • wrong Python environment
  • wrong module name
  • wrong project path
↑