Learn Courses My Dashboard

Trying to make a successfully Shift4Shop REST API call

Hello Chris, i know this is like a year later, but i am learning, i know you asked which API that we are interested in seeing you show how to connect, anyways, i need to connect to REST API Shift4Shop, to retrieve my orders, trying to create an app that will monitor my orders. i think i learned enough from your videos, the issue is the jsonObject format is a little confusing of what i need to put in it. so any help would be greatly appreciated. i can send you a link for the api documentation or the project i am working n so far. maybe i am asking too much, I did everything as you show in the How To Work With Any API (API Tutorial using URL Requests), i keep getting Error parsing response data.
i have the PrivateKey, the Token, i think i just need to know the format and what goes in the let jsonObject = , i need to get a list of my orders, i think i should use “GET”, but in your video you use “POST”
any help is appreciated.
i can send my project or the link for the REST API .
regards.
Ibrahim

here is my code ( my Private key & Token are correct on my end, but will alter them for security)

//  ViewController.swift
//  SlipGrip Mobile
//
//  Created by Ibrahim Kawar on 10/4/22.
//

import UIKit
class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        //URL
        let url = URL(string: "https://apirest.3dcart.com/3dCartWebAPI/v1/Orders?")
        guard url != nil else {
            print("Error creating url object")
        return
        }

        // URL Request
        var request = URLRequest(url: url!, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10)
        // Specify the header
        let header = ["Content-Type": "application/xml", "Accept": "application/json", "SecurURL": " https://slipgripcarmounts-com.3dcartstores.com/", "PrivateKey": "c8885c354e34876a35ad21d98429139b", "Token": "e3686bf39eae59a416a400e40306c57d5b"]
        request.allHTTPHeaderFields = header
        // Specify the body
        let jsonObject = ["url": "https://apirest.3dcart.com/3dCartWebAPI/v1/Orders?", "orderstatus": "NEW"]
        do {
            let requestBody = try JSONSerialization.data(withJSONObject: jsonObject, options: .fragmentsAllowed)
            request.httpBody = requestBody
        }
        catch {
            print("Error creating the data object fron json")
        }
        // Set the request type
        request.httpMethod = "POST"
        // Get the URLSession
        let session = URLSession.shared
        // Ceate the data task
        let dataTask = session.dataTask(with: request) { (data, response, error) in
        // check for errors
            if error == nil && data != nil {
                // try to parse out the data  
                do {
                    let dictionary = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String:Any]
                    print("THANK YOU LORD!!!")
                    print("Success: \(dictionary)")
            }
                catch {
                    print("Error parsing response data")
            }
        }
    }
        // Fire off the data task
    dataTask.resume()
    }

Yes please list the API docs for this and if you’re only doing a get request you generally don’t need any headers

You don’t need JSONSerialization, just use the JSONEncoder or JSONDecoder, depending on what you’re trying to do

Thank you so much for responding
Here is a link for the api resources

https://developer.3dcart.com/

I am
Only interested in Orders, connect and retrieve. List of new orders

Any sample
Code of how to format the request would be greatly appreciated

What do you mean by “connect?”

Here’s the list of endpoints, I’m guessing you want the first one? Any others?

Yes that’s correct, I have header parameters that need to be included for authentication, not sure how to add the with url call request.

Thank you so much

at this point, just the first one, i think once i see how the first one is done, i will be able to do the rest.
thank you
awaiting your response

A GET is used to fetch data, a POST is used to send data, these are HTTP methods. The main ones are GET, POST, PATCH, and DELETE

It seems like you’d probably be parsing the object wrong.

Also use JSONEncoder or JSONDecoder, not JSONSerialization

What does your model look like? The order model that you’re parsing from the request

Hello:
Yes, i am with you, i need to use the “GET” to fetch data, and i need to use the JSONDncoder and URLRequest. with the little experience i have because i am new at this, the problem i am having is how to include the Headers in the URLRequest such as ( the Token, The PrivateKey and The SecurURL, ( I have all these headers available, i am just know sure how to structure my request for the endpoint url to include these headers.
any help there would be great.
[
{
“InvoiceNumberPrefix”: “string”,
“InvoiceNumber”: 0,
“OrderID”: 0,
“CustomerID”: 0,
“OrderDate”: “2022-10-06T23:14:41.141Z”,
“OrderStatusID”: 0,
“LastUpdate”: “2022-10-06T23:14:41.141Z”,
“UserID”: “string”,
“SalesPerson”: “string”,
“ContinueURL”: “string”,
“AlternateOrderID”: “string”,
“OrderType”: “string”,
“PaymentTokenID”: 0,
“BillingFirstName”: “string”,
“BillingLastName”: “string”,
“BillingCompany”: “string”,
“BillingAddress”: “string”,
“BillingAddress2”: “string”,
“BillingCity”: “string”,
“BillingState”: “string”,
“BillingZipCode”: “string”,
“BillingCountry”: “string”,
“BillingPhoneNumber”: “string”,
“BillingEmail”: “string”,
“BillingPaymentMethod”: “string”,
“BillingOnLinePayment”: true,
“BillingPaymentMethodID”: “string”,
“ShipmentList”: [
{
“ShipmentID”: 0,
“ShipmentLastUpdate”: “2022-10-06T23:14:41.141Z”,
“ShipmentBoxes”: 0,
“ShipmentInternalComment”: “string”,
“ShipmentOrderStatus”: 0,
“ShipmentAddress”: “string”,
“ShipmentAddress2”: “string”,
“ShipmentAlias”: “string”,
“ShipmentCity”: “string”,
“ShipmentCompany”: “string”,
“ShipmentCost”: 0,
“ShipmentCountry”: “string”,
“ShipmentEmail”: “string”,
“ShipmentFirstName”: “string”,
“ShipmentLastName”: “string”,
“ShipmentMethodID”: 0,
“ShipmentMethodName”: “string”,
“ShipmentShippedDate”: “string”,
“ShipmentPhone”: “string”,
“ShipmentState”: “string”,
“ShipmentZipCode”: “string”,
“ShipmentTax”: 0,
“ShipmentWeight”: 0,
“ShipmentTrackingCode”: “string”,
“ShipmentUserID”: “string”,
“ShipmentNumber”: 0,
“ShipmentAddressTypeID”: 0
}
],
“OrderItemList”: [
{
“CatalogID”: 0,
“ItemIndexID”: 0,
“ItemID”: “string”,
“ItemShipmentID”: 0,
“ItemQuantity”: 0,
“ItemWarehouseID”: 0,
“ItemDescription”: “string”,
“ItemUnitPrice”: 0,
“ItemWeight”: 0,
“ItemOptionPrice”: 0,
“ItemAdditionalField1”: “string”,
“ItemAdditionalField2”: “string”,
“ItemAdditionalField3”: “string”,
“ItemPageAdded”: “string”,
“ItemAvailability”: “string”,
“ItemDateAdded”: “2022-10-06T23:14:41.141Z”,
“ItemUnitCost”: 0,
“ItemUnitStock”: 0,
“ItemOptions”: “string”,
“ItemCatalogIDOptions”: “string”,
“ItemSerial”: “string”,
“ItemImage1”: “string”,
“ItemImage2”: “string”,
“ItemImage3”: “string”,
“ItemImage4”: “string”,
“ItemWarehouseLocation”: “string”,
“ItemWarehouseBin”: “string”,
“ItemWarehouseAisle”: “string”,
“ItemWarehouseCustom”: “string”,
“RecurringOrderFrequency”: 0
}
],
“PromotionList”: [
{
“PromotionID”: 0,
“PromotionName”: “string”,
“Coupon”: “string”,
“DiscountAmount”: 0
}
],
“OrderDiscount”: 0,
“OrderDiscountCoupon”: 0,
“OrderDiscountPromotion”: 0,
“SalesTax”: 0,
“SalesTax2”: 0,
“SalesTax3”: 0,
“OrderAmount”: 0,
“AffiliateCommission”: 0,
“TransactionList”: [
{
“TransactionIndexID”: 0,
“OrderID”: 0,
“TransactionID”: “string”,
“TransactionDateTime”: “2022-10-06T23:14:41.141Z”,
“TransactionType”: “string”,
“TransactionMethod”: “string”,
“TransactionAmount”: 0,
“TransactionApproval”: “string”,
“TransactionReference”: “string”,
“TransactionGatewayID”: 0,
“TransactionCVV2”: “string”,
“TransactionAVS”: “string”,
“TransactionResponseText”: “string”,
“TransactionResponseCode”: “string”,
“TransactionCaptured”: 0
}
],
“CardType”: “string”,
“CardNumber”: “string”,
“CardName”: “string”,
“CardExpirationMonth”: “string”,
“CardExpirationYear”: “string”,
“CardIssueNumber”: “string”,
“CardStartMonth”: “string”,
“CardStartYear”: “string”,
“CardAddress”: “string”,
“CardVerification”: “string”,
“OfflinePaymentFieldList”: [
{
“InputName”: “string”,
“InputValue”: “string”
}
],
“RewardPoints”: “string”,
“QuestionList”: [
{
“QuestionAnswerIndexID”: 0,
“OrderID”: 0,
“QuestionID”: 0,
“QuestionTitle”: “string”,
“QuestionAnswer”: “string”,
“QuestionType”: “string”,
“QuestionCheckoutStep”: 0,
“QuestionSorting”: 0,
“QuestionDiscountGroup”: 0
}
],
“Referer”: “string”,
“IP”: “string”,
“CustomerComments”: “string”,
“InternalComments”: “string”,
“ExternalComments”: “string”
}
]

i will include the JSON model i am to fetch, just a few of the fields i am interested in and not everythin.

i am sorry to trouble you, i guess i just need to know how to include the headers in my URLRequest so that authentication can be accomplished on the REST API server side. once i know how to include the parameters in the request, I could figure out how to connect to the api and fetch the JSON response.

First I see you have application/xml but you should be using application/json

Do something like this:

func createURL() throws -> URL {
        var components = URLComponents()
        components.scheme = "https"
        components.host = "api.twitter.com"
        components.path = "/2/tweets"
        components.queryItems = [
            URLQueryItem(name: "ids", value: id),
            URLQueryItem(name: "expansions", value: "author_id,attachments.media_keys"),
            URLQueryItem(name: "tweet.fields", value: "created_at"),
            URLQueryItem(name: "user.fields", value: "profile_image_url,verified"),
            URLQueryItem(name: "media.fields", value: "preview_image_url,public_metrics,type,url")
   ]

   return completeURL
}

Also you could use async / await syntax, rather than closures

Just changed my answer btw

I tried with the components, and it was difficult to work with, i thought maybe the method you changed your mind about, seemed more friendlier to work with,
request.addValue.(). i just need to pass three headers
PrivateKey
SecureURL
and Tokin
in a get request.
i am new and the components seems to be difficult at my level, but i am eager to try.

Those are functions on URLComponents, and all the code is there that you’d need

How it adds it to the URL request is why I changed my response, passing header parameters is different than query parameters

You could also contact the API via their forum for specific information

thank you, i will try

If you can paste what you’ve written now and the models that may help. Including the changes to use JSONDecoder

Paste your code in as text, rather than providing a screenshot.

To format the code nicely, place 3 back-ticks ``` on the line above your code and 3 back-ticks ``` on the line below your code. The 3 back-ticks must be the ONLY characters on the line. The back-tick character is located on the same keyboard key as the tilde character ~ (which is located below the Esc key). You can also highlight an entire code block and click the </> button on the toolbar to wrap the block for you.

This also makes it easier for anyone assisting as they can copy the code and carry out some testing.