Engee documentation
Notebook

Searching Wikipedia articles by API

This example describes an example of working with the Wikipedia API from Engee, specifically sending a search query and displaying the search results.

Introduction

The Wikipedia API is a web service that provides access to wiki features such as authentication, page operations, search and other operations. The API is powered by the MediaWiki engine and uses the api.php handler written in PHP. You can use direct request submission or libraries to interact with the API. The handler accepts requests by sending HTTP requests to the handler's url.

Getting started

In this example, we'll use the HTTP.jl library to retrieve the results of a query by URL and the JSON.jl library to parser the response in JSON format.

Let's download and install the necessary libraries:

In [ ]:
import Pkg;
Pkg.add(["HTTP", "JSON"]);

Connect the libraries:

In [ ]:
using HTTP, JSON;

Function for searching Wikipedia articles

The following function generates a URL from a search query, sends a GET request, retrieves and prints out the the response to the query.

In [ ]:
function search_wikipedia(query::String)
    # Кодируем запрос для URL
    encoded_query = replace(query, " " => "%20")
    
    # Формируем URL для запроса к API Википедии
    url = "https://ru.wikipedia.org/w/api.php?action=query&list=search&srsearch=$encoded_query&format=json"
    
    # Отправляем GET-запрос
    response = HTTP.get(url)
    
    # Проверяем статус ответа
    if response.status != 200
        error("Ошибка при запросе к API Википедии: статус $(response.status)")
    end
    
    # Парсим JSON-ответ
    data = JSON.parse(String(response.body))
    
    # Извлекаем результаты поиска
    search_results = data["query"]["search"]
    
    # Выводим результаты
    if isempty(search_results)
        println("По вашему запросу ничего не найдено.")
    else
        println("Результаты поиска для \"$query\":")
        for result in search_results
            println("Заголовок: ", result["title"])
            println("Описание: ", result["snippet"])
            println("Ссылка: https://ru.wikipedia.org/wiki/", replace(result["title"], " " => "_"))
            println("-"^50)
        end
    end
end
Out[0]:
search_wikipedia (generic function with 1 method)

Programme operation

Let's pass the search query to the created function:

In [ ]:
# Пример использования
search_wikipedia("Julia programming language")
Результаты поиска для "Julia programming language":
Заголовок: Julia (язык программирования)
Описание: 24 мая 2013 года. Stephan Boyer. A Graphical Front End for the <span class="searchmatch">Julia</span> <span class="searchmatch">Programming</span> <span class="searchmatch">Language</span> (англ.). Массачусетский технологический институт (декабрь 2011)
Ссылка: https://ru.wikipedia.org/wiki/Julia_(язык_программирования)
--------------------------------------------------
Заголовок: Биоэквивалентность
Описание: Дата обращения: 9 июля 2019. Архивировано 9 июля 2019 года. The <span class="searchmatch">Julia</span> <span class="searchmatch">Programming</span> <span class="searchmatch">Language</span>  (неопр.). https://julialang.org. Дата обращения: 9 июня 2022
Ссылка: https://ru.wikipedia.org/wiki/Биоэквивалентность
--------------------------------------------------
Заголовок: LLVM
Описание: Graphical G <span class="searchmatch">Programming</span> <span class="searchmatch">Language</span>, Halide, Haskell, Java (байткод), JavaScript, <span class="searchmatch">Julia</span>, Kotlin, Lua, Objective-C, OpenGL Shading <span class="searchmatch">Language</span>, Ruby, Rust,
Ссылка: https://ru.wikipedia.org/wiki/LLVM
--------------------------------------------------
Заголовок: Python
Описание: 2007 года. Why We Created <span class="searchmatch">Julia</span>  (неопр.). <span class="searchmatch">Julia</span> website (февраль 2012). — «We want something as usable for general <span class="searchmatch">programming</span> as Python [...]». Дата обращения:
Ссылка: https://ru.wikipedia.org/wiki/Python
--------------------------------------------------
Заголовок: Хронология языков программирования
Описание: <span class="searchmatch">programming</span> <span class="searchmatch">language</span> Проект Bend развивает высокоуровневый язык для параллельных вычислений на GPU Online encyclopedia for the history of <span class="searchmatch">programming</span>
Ссылка: https://ru.wikipedia.org/wiki/Хронология_языков_программирования
--------------------------------------------------
Заголовок: Язык программирования
Описание: Ward. <span class="searchmatch">Language</span> Oriented <span class="searchmatch">Programming</span>. — Computer Science Department, Science Labs, 1994. Ian Joyner. A Critique of C++ and <span class="searchmatch">Programming</span> and <span class="searchmatch">Language</span> Trends
Ссылка: https://ru.wikipedia.org/wiki/Язык_программирования
--------------------------------------------------
Заголовок: Processing
Описание: Processing <span class="searchmatch">Language</span> (1st ed.), Wiley, p. 384, ISBN 0-470-37548-5 Reas, Casey; Fry, Ben; Maeda, John (30 сентября 2007), Processing: A <span class="searchmatch">Programming</span> Handbook
Ссылка: https://ru.wikipedia.org/wiki/Processing
--------------------------------------------------
Заголовок: Гомоиконичность
Описание: 3 марта 2016 на Wayback Machine, Digital Humanities 2012 conference proceedings. <span class="searchmatch">Language</span> Notes for <span class="searchmatch">Programming</span> <span class="searchmatch">Language</span> Experts (недоступная ссылка)
Ссылка: https://ru.wikipedia.org/wiki/Гомоиконичность
--------------------------------------------------
Заголовок: Старение мозга
Описание: Tang, Yizhe; Zhang, Hai; Yin, Ye; Li, Bo; et al. (2013). &quot;Hypothalamic <span class="searchmatch">programming</span> of systemic ageing involving IKK-[bgr], NF-[kgr]B and GnRH&quot;. Nature.
Ссылка: https://ru.wikipedia.org/wiki/Старение_мозга
--------------------------------------------------
Заголовок: Content Management Framework
Описание: application frameworks with regards to rapid development Bestwebframeworks, Choose your <span class="searchmatch">programming</span> <span class="searchmatch">language</span> to compare web frameworks Web Framework Benchmarks
Ссылка: https://ru.wikipedia.org/wiki/Content_Management_Framework
--------------------------------------------------

The created function, as you can see, generates an answer according to the search query we generated for it.

Conclusion

In this example, we used Engee's capabilities and Julia language libraries to work with HTTP requests and JSON objects to generate and extract a search query to the Russian Wikipedia.