Site icon Ravi Shankar

Understanding REST and HTTP: Making API Calls in iOS with Swift

In the world of web and mobile development, you’ll often hear terms like REST and HTTP. These concepts are fundamental to building robust applications that communicate with servers over the internet. In this blog post, we will explore the differences between REST and HTTP and learn how to make API calls in iOS using Swift.

Overview

What is HTTP?

HTTP, or Hypertext Transfer Protocol, is the foundation of any data exchange on the web. It is a protocol used for transferring hypertext requests and information between web servers and browsers. HTTP follows a request-response model where a client sends a request to a server, and the server sends back a response.

Key Characteristics of HTTP:

What is REST?

REST, or Representational State Transfer, is an architectural style for designing networked applications. It is a set of guidelines that developers follow when creating APIs that enable clients to interact with servers. RESTful APIs use HTTP methods and principles to perform CRUD (Create, Read, Update, Delete) operations on resources.

Key Principles of REST:

Differences between REST and HTTP

Making API Calls in iOS with Swift

Now that we understand the basics of HTTP and REST, let’s dive into making API calls in iOS using Swift. We’ll use the URLSession class to perform network requests and handle responses.

Example: Fetching Expenses from a REST API
  1. Setting Up the Project Create a new iOS project in Xcode and add the following code to your view controller.
  2. Define the Expense Model
   struct Expense: Codable {
       let id: Int
       let category: String
       let amount: Double
       let description: String
   }
  1. Make an API Call
   import UIKit

   class ViewController: UIViewController {
       override func viewDidLoad() {
           super.viewDidLoad()
           fetchExpenses()
       }

       func fetchExpenses() {
           guard let url = URL(string: "https://api.example.com/expenses") else { return }

           let task = URLSession.shared.dataTask(with: url) { data, response, error in
               if let error = error {
                   print("Error: \(error.localizedDescription)")
                   return
               }

               guard let httpResponse = response as? HTTPURLResponse,
                     (200...299).contains(httpResponse.statusCode) else {
                   print("Invalid response")
                   return
               }

               guard let data = data else {
                   print("No data")
                   return
               }

               do {
                   let expenses = try JSONDecoder().decode([Expense].self, from: data)
                   DispatchQueue.main.async {
                       self.displayExpenses(expenses)
                   }
               } catch {
                   print("JSON Decoding Error: \(error.localizedDescription)")
               }
           }

           task.resume()
       }

       func displayExpenses(_ expenses: [Expense]) {
           for expense in expenses {
               print("\(expense.category): $\(expense.amount) - \(expense.description)")
           }
       }
   }
Explanation
  1. Define the Expense Model: We create a struct called Expense that conforms to the Codable protocol, making it easy to encode and decode JSON data.
  2. Make an API Call:

Conclusion

Understanding the differences between REST and HTTP is crucial for building networked applications. HTTP is the protocol that enables data transfer over the web, while REST is an architectural style that defines how to interact with resources using HTTP methods.

In iOS development, making API calls using URLSession and handling JSON data with Codable are essential skills. By following the examples provided, you can fetch data from RESTful APIs and integrate it into your Swift applications.

Feel free to explore more advanced topics like error handling, asynchronous operations, and data persistence to further enhance your app’s networking capabilities.


Exit mobile version