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