Engee documentation
Notebook

Search for Wikipedia articles via API

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

Introduction

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

Getting started

In this example, we will use the library HTTP.jl to get the results of a URL request and a library JSON.jl to parse the response in JSON format.

Download and install the necessary libraries:

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

Connecting libraries:

In [ ]:
using HTTP, JSON;

A function for searching articles from Wikipedia

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

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)

Program operation

Passing 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
--------------------------------------------------

As you can see, the created function generates an answer according to the search query that we have created for it.

Conclusion

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