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)
# Encoding the request for the URL
encoded_query = replace(query, " " => "%20")
# Creating a URL for a request to the Wikipedia API
url = "https://ru.wikipedia.org/w/api.php?action=query&list=search&srsearch=$encoded_query&format=json"
# Sending a GET request
response = HTTP.get(url)
# Checking the response status
if response.status != 200
error("Error when requesting the Wikipedia API: status $(response.status)")
end
# Parsing the JSON response
data = JSON.parse(String(response.body))
# Extracting the search results
search_results = data["query"]["search"]
# We display the results
if isempty(search_results)
println("Nothing was found for your search.")
else
println("Search results for \"$query\":")
for result in search_results
println("Heading: ", result["title"])
println("Description: ", result["snippet"])
println("The link: https://ru.wikipedia.org/wiki/", replace(result["title"], " " => "_"))
println("-"^50)
end
end
end
Program operation
Passing the search query to the created function:
# Usage example
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.