In this section, we define an API client that will connect to the Merriam-Webster dictionary REST API. Unlike the Oxford Dictionary API, where authentication credentials are provided via the header fields of the API request, the api key appended to the URL string. Furthermore, the only query parameter of concern is that of the word we want to look up. As with the Oxford API client, we will similarly define a struct for the API request (i.e.MWAPIRequest, an abbreviated form for Merriam-Webster API Request), a delegate protocol for handling the different possible server responses, and API client class. For the Merriam-Webster API client, we will be making use of KissXML, a third-party library for parsing XML data, since REST API for Merriam-Webster provides data in XML-formatted data.
Rather than using the native XMLParser class, which functions as a SAX parser that calls delegate methods as it walks through each of the elements in the node tree, we will use KissXML to convert the XMLData to DOM structure whose element tags can then be filtered and parsed using XPath syntax.
To begin with, we define a struct for the Merriam-Webster API request as show below:
struct MWAPIRequest{ let baseURL = "https://www.dictionaryapi.com/api/v1/references/collegiate/xml/" let apiDictionaryKey = "99fddaa-fdfas-4d0e-fd88-8fdad" let apiThesaurusKey = "ad888-fdf88-fddf-8fdd-adf888df" var headWord: String var isRequestForThesaurusAPI = false init(withHeadWord userHeadWord: String, isThesaurusRequest: Bool){ self.headWord = userHeadWord self.isRequestForThesaurusAPI = isThesaurusRequest } func generateURLRequest() -> URLRequest{ let urlString = getURLString() let url = URL(string: urlString)! return getURLRequest(forURL: url) } private func getURLRequest(forURL url: URL) -> URLRequest{ let request = URLRequest(url: url) /** Configure any header fields if necessary for the API Request **/ return request } private func getURLString() -> String{ let wordURL = baseURL.appending(self.headWord) let apiKey = self.isRequestForThesaurusAPI ? apiThesaurusKey : apiDictionaryKey let processedURL = wordURL.appending("?key=\(apiKey)") return processedURL } }
As can be seen above, the intializer only requires the headword and a boolean flag indicating whether we wish to connect to the Thesaurus API or the Collegiate Dictionary API, both of which use different API keys, which are stored as static constants in the struct. As was the case with OxfordAPIRequest struct, the API keys used here are totally arbitrary and will not work if you are implementing the code for personal use. Be sure to apply for an API key from the Merriam-Webster website.
To continue, please click here
If you feel confused or are having trouble following, you can go back to the previous page or back to the table of contents table of contents.