SamB SamB - 1 month ago 7
PHP Question

How to write a python script to call a API and print the results retrieved from the API

I am a beginner and new to coding. I have an API in php gives the some meteo data retrieved from a meteo station. i want to have a python script which will call the API and print the results from the API in a file. Please suggest me the right coding approach. The API is:
http://ewodr.wodr.poznan.pl/doradztwo/swd/meteo_api.php?dane={"token":"pcss","id":303,"operacja":"odczyt_doba"}

Answer

Use the urllib2 library (for python 2) to fetch the data from the API. It could look something like this:

import urllib2
import csv  

        # API url
        url = "your API url"

        # open the api url
        response = urllib2.urlopen(str(url))

        data = response.read()

        # write the results in a csv file
        with open('file.csv', 'wb') as f:
            f.write(data)

or if JSON

import json
import urllib2  

        # API url
        url = "your API url"

        # open the api url
        response = urllib2.urlopen(str(url))

        data = json.load(response) 

        # write the results in a csv file
        with open('file.txt', 'w') as f:
            json.dump(data, f)

I have not used it with python 3 but I do not think there is a lot of changes.