connect to imgb api in swift

To connect to ImgB API in Swift, follow the below steps:

  1. First, create an API key for ImgB API at https://api.imgb.com/signup.

  2. Import the required frameworks for HTTP requests i.e., Foundation and UIKit.

  3. Create a function to make HTTP Request to ImgB API with the API key in the header.

    main.swift
    func requestDataFromImgBApi() {
        
        let apiKey = "Your API Key"
        let apiUrl = "https://api.imgb.com/api/v1/your/endpoint"
        
        guard let url = URL(string: apiUrl) else {
            print("Invalid URL")
            return
        }
        
        var request = URLRequest(url: url)
        request.httpMethod = "GET"
        request.addValue(apiKey, forHTTPHeaderField: "apikey")
        
        let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
            guard let data = data, error == nil else {
                print(error?.localizedDescription ?? "Invalid Data")
                return
            }
            
            if let responseString = String(data: data, encoding: .utf8) {
                print("Response Data: \(responseString)")
            }
        }
        
        task.resume()
    }
    
    776 chars
    28 lines

    In the function above, replace "Your API Key" with the actual API key that you created.

  4. Call the function where required.

    main.swift
    requestDataFromImgBApi()
    
    25 chars
    2 lines

Note: Make sure to replace "your/endpoint" with the actual endpoint that you want to access from ImgB API.

related categories

gistlibby LogSnag