import requests
import json


def query_sparql(entities, language="en"):
    """
    Perform SPARQL query for item and property.

    Build SPARQL query with item ID and property ID from enitities dictionary
    and run it on SPARQL endpoint at Wikidata.

    Parameters:
    entities (dict): dictionary with ['property']['id']
                     and ['item']['id'] set
    language (str): (optional) language code for query (default "en").

    Returns:
    answer: String with label of the result of the query
    """
    item = entities['item']['id']
    property = entities['property']['id']
    endpoint = "https://query.wikidata.org/bigdata/namespace/wdq/sparql"
    sparql = "SELECT ?answerLabel WHERE {\n"
    sparql = sparql + "wd:{} wdt:{} ?answer.".format(item, property)
    sparql = sparql + "\nSERVICE wikibase:label "
    sparql = sparql + '{bd:serviceParam wikibase:language "'
    sparql = sparql + language + '".}\n}'
    query = requests.get(endpoint + "?query=" + sparql + "&format=json")
    answer = json.loads(query.text)
    answer = answer['results']['bindings'][0]['answerLabel']['value']
    return answer