Fetch & Parse API Data with Swift

Kelsey Creehan
3 min readFeb 9, 2021

--

Time to play fetch!

Most apps out there rely on some external source of data, so learning how to retrieve data from an API and integrate it into your app is a necessity. It’s likely you already have an API in mind, but if not, I’ll be using the Rick and Morty API as an example.

Get the data

  • Check the API documentation to see how the data is structured or nested
  • Decide which key/value pairs from the data you’re interested in using in your app
  • Create a new Swift file
  • Create a struct that inherits from the Codable protocol, which is what should allow us to decode the JSON response. In my case, I’m calling the struct “CharacterList”, since the plan is to render a list of characters from the API
  • Create another file and struct that will represent each instance of the data you want to add to the list. I titled this one “Character.” This also needs to follow the Codable protocol
  • Within the struct, start creating variables for the key/value pairs you want. Name the variables the same (it’s not required, but makes things easier.)
  • If it’s possible the value may be nil, you need to make that variable into an optional. If you set the variable equal to a different type, like an empty string, your app could crash when it gets a nil value instead
  • I’m going to create variables for the character’s name, status, and species, all of which will be optional strings
  • I’m going to create variables for the character’s name, status, and species, all of which will be optional strings
  • Back in the CharacterList struct, create a variable that represents the array of characters we want to display (I’m making it optional just in case the API ever returns nil,, although it’s unlikely), like so: var characters:[Character]?
  • Now, in the ViewController file, add a variable with the URL string within the viewDidLoad method (just for the purposes of this exercise — it would likely go somewhere else normally)
  • Next, add a guard just in case the url is nil
  • Create a URL session

Parse the data

  • Create a data task to make the API call and run a code block on return — the data can be force unwrapped since we already checked for nil above
  • We do, however, need to check for errors in the parsing process
  • Create a new JSONDecoder instance, and then within a do/catch block, parse the response into a constant called characterList where the data is passed into the decoder
  • Print an error within the catch block
  • At the end of the struct, be sure to invoke the API call with dataTask.resume()
  • Check your console to ensure the values printed as intended

What’s Next: We already created structs to map the JSON objects to and display within the app. Watch out for Part 2, where we’ll actually display the data on the user interface.

--

--