_DudeWhat_

Wikipedia API

Jan 7th, 2022 (edited)
489
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 0.83 KB | None | 0 0
  1. local wikipedia = {}
  2.  
  3. local function request(url)
  4.     local valid, reason = http.checkURL(url)
  5.     if not valid then print("URL is invalid:", reason) return nil end
  6.     local response, reason, err = http.get(url)
  7.     if not response then print("Request failed:", reason) return nil end
  8.     return response.readAll()
  9. end
  10.  
  11. local function jsonrequest(url)
  12.     local response = request(url)
  13.     if not response then return nil end
  14.     local result, reason = textutils.unserializeJSON(response)
  15.     if not result then print("Deserialization failed:", reason) return nil end
  16.     return result
  17. end
  18.  
  19. function wikipedia.search(query)
  20.     local srsearch = textutils.urlEncode(query)
  21.     local url = "http://en.wikipedia.org/w/api.php?action=query&list=search&format=json&srsearch="..srsearch
  22.     local response = jsonrequest(url)
  23.     return response
  24. end
  25.  
  26. return wikipedia
Add Comment
Please, Sign In to add comment