Create Custom Data Models for API in Swift

Level: Beginner

Sreejith NP
2 min readJun 28, 2023

Creating custom Data Models in Swift is a major step in parsing an API and using it in your iOS Application

Here is a step by step guide to create custom Data model structs to decode your API response.

Step1: First you need to paste your api url ,either in your browser or services like postman and get the JSON response of your API as shown below.

For example :

{

“name”: “John Doe”,

“age”: 26,

“email”: “john.doe@example.com”,

}

This is a simple JSON response which contains data as key — value pairs. So this is similar to a dictionary in Swift.

Copy this JSON response including the the starting and ending curly braces { }

Step 2: Go to the website https://app.quicktype.io

On the left side of the webpage there is an input pane where we can paste our json response that we have copied in the above step as given below in the sample image.

Paste you json in this pane in the webpage

In the Name field ,enter the name that you want for your struct.Here I have given it as “Person”

Step 3: On the right side of the input pane ,you will instantaneously get the custom model in swift as a struct

Custom Struct Model for JSON in Swift

Copy the generated struct model and use it in your code by creating a new swift file and paste the code in it just as shown below.

Note: It is generally a standard practice to name the new swift file as the same name as that of the struct and that too starting with a capital letter.

Here we have named both the swift file and the struct as “Person” where P is capitalised.

You can easily generate models for even complex API responses through this website.

Tip: Always Ensure that the struct is conforming to Codable protocol.Only then the JSON response from our API can be decoded in the form of our custom model.

--

--