Search code examples
curlnsurlconnectionafnetworkingsquaresquare-connect

AFNetworking Square API


I'm really stumped on this. I need to convert this cURL command into objective-c. I am using the AFNetworking library to go about this but it returns bad request (error 400) each time. I'd appreciate help.

cURL command:

curl -X POST -H "Content-Type: application/json" -H "Authorization: Bearer XXXXXXXXXXXXX" -d '{"quantity_delta": -5,"adjustment_type": "SALE"}' https://connect.squareup.com/v1/me/inventory/00CC0141-C50C-4A7A-9FAA-368EC79DA652

AFNetworking Objective-C Code:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager.requestSerializer setValue:@"Bearer XXXXXXXXXXXXX" forHTTPHeaderField:@"Authorization"];
[manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

NSDictionary *parameters = @{@"quantity_delta": [NSNumber numberWithInt:-1], @"adjustment_type": @"SALE"};
NSLog(@"Parameters are %@", parameters);

[manager POST:@"https://connect.squareup.com/v1/me/inventory/00CC0141-C50C-4A7A-9FAA-368EC79DA652" parameters:@{@"quantity_delta": [NSNumber numberWithInt:-1], @"adjustment_type": @"SALE"} success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

Solution

  • Fair warning that I'm new to the AFNetworking library, but I was able to make a successful request by adding the line in bold between the first two lines of the above sample:

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager setRequestSerializer:[AFJSONRequestSerializer serializer]];
    [manager.requestSerializer setValue:@"Bearer XXXXXXXXXXXXX" forHTTPHeaderField:@"Authorization"];
    

    It appears that by default, the AFHTTPRequestOperationManager uses the AFHTTPRequestSerializer, which does not format JSON bodies correctly out of the box. Using the AFJSONRequestSerializer subclass instead resolves this issue.