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:
import Pkg;
Pkg.add(["HTTP", "JSON"]);
Connecting libraries:
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.
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
Program operation
Passing the search query to the created function:
# Пример использования
search_wikipedia("Julia programming language")
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.