---
# System prepended metadata

title: API
tags: [UPN, srednja sola]

---

FREE APIS: https://github.com/public-apis/public-apis

# UVOD
## Delovanje dictionary
```python=
import requests
import pprint #pretty print - naredi lepši print dictionaryjev

#dictionary
dict = {"Ime" : "Maša",
       "Starost" : 17,
       "Zaposlen" : False,
       "Siblings" : ["Ančka", "Teja"]
       }

print(dict["Ime"], dict["Siblings"][1], dict["Zaposlen"])
print(dict.get("Ime2", 0)) #če tega imena v dict ni, izpiše dano vrednost(0)
```
![image](https://hackmd.io/_uploads/H1ip-H746.png)

---------------------------------------------------------------
## Klic random api - karte
API: https://deckofcardsapi.com/
```python=
import requests
import pprint 

url = "https://deckofcardsapi.com/api/deck/new/shuffle/?deck_count=1"

#klic api: karte
call = requests.get(url).json()

print(call["deck_id"])
```
![image](https://hackmd.io/_uploads/BkehZSXEp.png)

---

## klic api - openweather
API: https://openweathermap.org/api
```python=
import requests
import pprint

api_key = "5f5c8f523ca2bf8d20d9babb8676c5f4"
# 46.23280523059815, 14.367835593838434 - kordinate
payload = {"lat" : 46.23280523059815,
         "lon" : 14.367835593838434,
         "appid" : api_key
         }

base_url = "https://api.openweathermap.org/data/2.5/weather"

#base urlju dodamo še določene parametre, da pridemo do podatkov
call = requests.get(base_url, params = payload)
json = call.json()
print(call.url)
print(json)
```

![image](https://hackmd.io/_uploads/SJmwdHXNa.png)

---------------------------------------------------------------

## napaka, če kličes dictionary, ki je v seznamu
![image](https://hackmd.io/_uploads/B1DENd2VT.png)


### Pogled podnebja v tvojem kraju
API: https://api.openweathermap.org
```python=
import requests
import pprint

api_key = "5f5c8f523ca2bf8d20d9babb8676c5f4"

# 46.23280523059815, 14.367835593838434 - kordinate(Kranj)
payload = {"lat" : 46.23280523059815,
         "lon"   : 14.367835593838434,
         "units" : "metric",
         "lang"  : "SL",
         "appid" : api_key
         }

sezMest = []

base_url = "https://api.openweathermap.org/data/2.5/weather"
call = requests.get(base_url, params = payload)
json = call.json()
print(json["weather"][0]["description"])
```
![image](https://hackmd.io/_uploads/SygbV_2NT.png)

---------------------------------------------------------------

## najvišja temperatura od nekaterih mest
Mesta: Ljubljana, Maribor, Koper, Bled,Celje
API: https://api.openweathermap.org

```python=
import requests
import pprint #pretty print

 #sezMest = [mesto, lan, lot]
sezMest = [["Ljubljana", 46.056946, 14.505751], ["Maribor", 46.554650, 15.645881], ["Koper", 45.548059, 13.730188], ["Bled", 46.361618, 14.095287], ["Celje", 46.23092, 15.26044]]
api_key = "5f5c8f523ca2bf8d20d9babb8676c5f4"

def najvisja_temperatura(vsa_mesta, api):
  base_url = "https://api.openweathermap.org/data/2.5/weather"
  max = float("-inf")  #-infinity
  #min = float("inf")  infinity
  
  for mesto in sezMest:
      # posamezno gre čez mesta
      payload = {"lat" : mesto[1],
                "lon"   : mesto[2],
                "units" : "metric",
                "lang"  : "SL",
                "appid" : api_key
                }
      call = requests.get(base_url, params = payload).json()
      
      #pogleda, če je temperatura višja od najvišje
      if call["main"]["temp"] > max:
        max = call["main"]["temp"]
        
  #poišče mesto z najvišjo temperaturo
  for mesto in sezMest:
    payload = {"lat" : mesto[1],
              "lon"   : mesto[2],
              "units" : "metric",
              "lang"  : "SL",
              "appid" : api_key
              }
    call = requests.get(base_url, params = payload).json()
    if call["main"]["temp"] == max:
      return mesto[0]
    
print(najvisja_temperatura(sezMest, api_key))
```
![image](https://hackmd.io/_uploads/ryHsn_3Va.png)

---------------------------------------------------------------

## send sms api
```python=
import requests
import pprint #pretty print

url = 'http://www.smsapi.si/poslji-sms'
payload = {"un"  : "masa_zvan",
          "ps"  : "ddf4fb48da8298dae3ac0c49ff9931abb2ef22a6aa",
          "from": "031480333",
          "to"  : "040837950",
          "m"   : "Helooooo api sms dela",
          "cc"  : "386"
          }

k = requests.get(url, params = payload)
print(k.text)
```

# VAJE
## Vaja 1:
Navodilo: Za vsako število od 1 do 100 s pomočjo API-ja izpiši matematično in trivia dejstvo.

Poskusi urediti pregleden izpis.

API: http://numbersapi.com/
```python=
import requests

# zanka, ki gre od 1-100
for st in range(1, 101):
  print(requests.get(f"http://numbersapi.com/{st}/trivia").text)
```

![image](https://hackmd.io/_uploads/SyM_cv7HT.png)

----------------------------------------------------------

## Klici food api
API: https://spoonacular.com/food-api/docs
### random recepie
```python=
import requests
import pprint

apikey = "9db7752df12545b5b1380261af14a1ae"
base_url = "https://api.spoonacular.com/recipes/random"
params = {
    "limitLicense": True,
    "number": 2,
    "apiKey": apikey
}

call = requests.get(base_url, params=params).json()
recipes = call["recipes"]

#okoli po seznamu receptov
for st in range(params["number"]):
  pprint.pprint(recipes[st]) #prikazovanje receptov
  print("------------------------------------------------")

```
![image](https://hackmd.io/_uploads/HJzvxp1oT.png)


---

### zamenjava za dolocene sestavine
```python=
import requests
import pprint

apikey = "9db7752df12545b5b1380261af14a1ae"
base_url = "https://api.spoonacular.com/food/ingredients/substitutes"
params = {"ingredientName" : "butter",
          "apiKey"         : apikey
}

call = requests.get(base_url, params=params).json()
pprint.pprint(call)

```
![image](https://hackmd.io/_uploads/r1cxbTkia.png)

------------------------------------------

### pretvorba iz gram v cups
```python=
import requests
import pprint

apikey = "9db7752df12545b5b1380261af14a1ae"
base_url = "https://api.spoonacular.com/recipes/convert"
params = {"ingredientName" : "flour",
          "sourceAmount"   : 1,
          "sourceUnit"     : "grams",
          "targetUnit"     : "cups",
          "apiKey"         : apikey
}

call = requests.get(base_url, params=params).json()
pprint.pprint(call["answer"])
```

![image](https://hackmd.io/_uploads/HkeP-a1ip.png)

------------------------------

### sestavina v carbonari
```python=
import requests
import pprint

apikey = "9db7752df12545b5b1380261af14a1ae"
base_url = "https://api.spoonacular.com/recipes/guessNutrition"
params = {"title"  : "Carbonara",
          "apiKey" : apikey
}

call = requests.get(base_url, params=params).json()
pprint.pprint(call["carbs"])

```
![image](https://hackmd.io/_uploads/BkpZshHrT.png)

-------------------------------------

### vina, ki pašejo zravn zrezka
```python=
import requests
import pprint

apikey = "9db7752df12545b5b1380261af14a1ae"
base_url = "https://api.spoonacular.com/food/wine/pairing"
params = {"food"  : "steak",
          "apiKey" : apikey
}

call = requests.get(base_url, params=params).json()
pprint.pprint(call["pairedWines"])

```
![image](https://hackmd.io/_uploads/SJWHh3rHa.png)


## VAJE
1. Seznam vseh sposobnosti poljubnega Pokémona (Uporaba Pokémon API)
2. Iskanje aktivnosti glede na kriterije (Uporaba Bored API)
3. Odkrivanje dejstev o sadju (Uporaba Trefle API)
4. Sledenje Mednarodni vesoljski postaji
   ├── 4.1 Sledenje lokaciji MVP
   └── 4.2 Kako daleč je MVP od mene zdaj? (Zahteva vnos vaše lokacije)
       └── Vnesite vašo lokacijo (Zemljepisna širina, Zemljepisna dolžina): [Vnos uporabnika]
5. Prevedite slovensko besedo skozi N prevodov in nazaj v slovenščino


## Navodila
1.  **Seznam vseh sposobnosti izbranega Pokemona (Pokémon API):**
Pridobi vse sposobnosti izbranega Pokemona iz Pokémon API-ja. Uporabite API: https://pokeapi.co. 
Skripta naj nato izvleče in prikaže seznam sposobnosti, ki jih Pikachu poseduje.
```python=
import requests
import pprint

pokemon = input("Vnesi pokemona: ")
base_url = f"https://pokeapi.co/api/v2/pokemon/{pokemon}"
payload = {
    pokemon: pokemon,
}

call = requests.get(base_url).json()
for s in call["abilities"]:
  pprint.pprint(s["ability"]["name"])
```
![image](https://hackmd.io/_uploads/SJmuDOEUT.png)

---

2. **Iskanje aktivnosti glede na kriterije (Bored API):**
Ustvarite funkcijo, ki bo sprejela parametre, kot so cena, število ljudi in število aktivnosti, ter uporabila Bored API za iskanje primernih aktivnosti. Uporabite naslovno točko: http://www.boredapi.com. Skripta naj pošlje zahteve na Bored API s podanimi parametri in vrne seznam predlaganih aktivnosti.
```python=
import requests
import pprint


def bored_api(cena, st_ljudi, st_aktivnosti):
  base_url = f"https://www.boredapi.com/api/activity"
  payload = {
      "maxprice": cena,
      "participants": st_ljudi,
  }



  for st in range(st_aktivnosti):
    call = requests.get(base_url, params=payload).json()
    pprint.pprint(call.get("activity", "Nič ne najdem!"))


cena = int(input("cena: "))
ljudje = int(input("st_ljudi: "))
aktivnosti = int(input("st_aktivnosti: "))

bored_api(cena, ljudje, aktivnosti)

```
![image](https://hackmd.io/_uploads/SJg5lKEUT.png)

---

3. **Odkrivanje dejstev o sadju (Trefle API):**
Napišite skripto, ki omogoča vnos imena sadja in izvedbo iskanja petih zanimivih dejstev o njem prek Trefle API-ja. Uporabite naslovno točko: https://trefle.io. Skripta naj razčleni odgovor API-ja in izvleče informacije, kot so znanstveno ime, družina, rod in druge zanimive podrobnosti. Nato izpiši še 5 poljubnih dejstev o sadju.
```python=
import requests
import pprint


def fruit_api(name):
  api = "Qdxddwe4MM3WZgX3pf8YC77RBqqUwGZ5F7Qf74itG-Y"
  base_url = "https://trefle.io/api/v1/species/search"
  payload = {
      "token" : api,
      "q" : name
    }

  call = requests.get(base_url, params = payload).json()
  
  data = call["data"][0]
  print(data["common_name"])
  print(data["family"])
  print(data["scientific_name"])
  print(data["genus"])
  print(data["image_url"])
  


name = input("Ime sadja: ")
fruit_api(name)
```

---

4. **Sledenje MVP (Mednarodna vesoljska postaja):**
    1.  Sledenje lokaciji MVP:
Izpiši trenutno lokacijo MVP.
    1. Razdalja do MVP:
    Vnesite svojo trenutno lokacijo (zemljepisno širino in dolžino) in izračunajte razdaljo med vašo lokacijo in trenutno lokacijo MVP.
    **po spletu poišči kako izračunamo razdaljo med dvema koordinatama**
```python=

```

---

5. **Prevedite slovensko besedo skozi N prevodov in nazaj v slovenščino:**
Ta naloga vključuje večkratno prevajanje slovenske besede in nato povratno prevajanje v slovenščino. Omogočite uporabniku, da določi število prevodov (N) in vpiše besedo za prevajanje. Skripta naj prevede besedo skozi N prevodov (naključnih jezikov) in jo nato ponovno prevede v slovenščino za končni rezultat. Uporabi poljuen API
**implementacija čez katere jezike gre prevod je poljubna.**

```python=

```
