rdediana | Posts: 23

REST - POST Package JSON + Documents Assistance

0 votes
Hello, still in exploratory stages at the moment. does that team has an example to share the illustrates how, using objectivec, one could http POST both a json package and document to sign using the REST api? i'm trying to achieve the same outcome as the PYTHON script; simply replicate in objectivec. any assistance would be greatly appreciated!! the python script makes it look to easy!
# test1 for creating package
# payload = codecs.open('package.json', 'r',encoding='utf8').read()
# print(payload)
# documents = {'file': open(os.getcwd()+'/newaccount-v1.pdf', 'rb').read()}
# print("creating package")
# print(client.create_package_multipart(payload, documents))
# test1 end
cheers.

Approved Answer
mwilliams | Posts: 957

Reply to: REST - POST Package JSON + Documents Assistance

0 votes
Hello rdediana, Sorry for the delay. I had some major computer issues that had me mostly down for a couple weeks and I forgot to make sure this was followed up on. I apologize. You can definitely use templates within eSignLive to house the documents and use the REST API to provide an update to the package JSON. I have gotten the following sample from our mobile team where it looks like they're showing how to do the entire multipart form in objective C vs using a template. I also have a sample application I can load into our code share, if you think that would be helpful. If this isn't what you're looking for, let me know. :) Sorry again for the delay.
NSString *payload = @"{\"status\": \"DRAFT\",\"roles\": [{\"id\": \"signer1\",\"signers\": [{\"email\": \"[email protected]\",\"firstName\": \"Qamar\",\"lastName\": \"Suleiman\"}]}],\"documents\": [{\"description\": \"this is description\",\"approvals\": [{\"role\": \"signer1\",\"fields\": [{\"type\":\"SIGNATURE\",\"subtype\": \"FULLNAME\",\"page\": 0,\"top\": 100,\"left\": 100,\"width\": 200,\"height\": 60}]}],\"name\": \"Document1\"}],\"name\": \"TransactionTest\"}";
    
    
    
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"testPDF" ofType:@"pdf"];
    NSData *fileData = [NSData dataWithContentsOfFile:filePath];
    
    
    NSString *serverAPIURL = @"https://sandbox.esignlive.com";
    NSURL *url = [NSURL URLWithString:[serverAPIURL stringByAppendingPathComponent:@"api/packages"]];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    
    /* 
     We Could Either use the Session token or the API Key
     */
    
    NSString *sessionToken = @"";
    sessionToken = nil;
    if (sessionToken) {
        NSDictionary *cookieProperties = [NSDictionary dictionaryWithObjectsAndKeys:
                                          serverAPIURL, NSHTTPCookieDomain,
                                          @"\\", NSHTTPCookiePath,
                                          @"ESIGNLIVE_SESSION_ID", NSHTTPCookieName,
                                          sessionToken, NSHTTPCookieValue,
                                          nil];
        
        NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieProperties];
        NSArray* cookieArray = [NSArray arrayWithObjects: cookie, nil];
        NSDictionary * headers = [NSHTTPCookie requestHeaderFieldsWithCookies:cookieArray];
        [request setAllHTTPHeaderFields:headers];
    }
    else
    {
        NSString *apiKEY = @"";
        [request setValue:[NSString stringWithFormat:@"Basic %@",apiKEY] forHTTPHeaderField: @"Authorization"];
    }
    
    
    [request setHTTPMethod:@"POST"];
    
    //setup the body
    
    NSString *boundary = @"---------------------------14737809831466499882746641449";
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
    [request addValue:contentType forHTTPHeaderField: @"Content-Type"];
    
    NSMutableData *body = [NSMutableData data];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"payload\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[payload dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file\"; filename=\"%@\"\r\n",[filePath lastPathComponent]] dataUsingEncoding:NSUTF8StringEncoding]];
    
    [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    
    [body appendData:fileData];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    
    [request setHTTPBody:body];
    
    
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue new] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        
        
        NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
        NSLog(@"%@",responseDict);
        
        
    }];

mwilliams | Posts: 957

Reply to: REST - POST Package JSON + Documents Assistance

0 votes
Trying to get someone with objectivec experience to help with this. What have you tried so far that is not working?

rdediana | Posts: 23

Reply to: REST - POST Package JSON + Documents Assistance

0 votes
at the moment this is what i've tried. UTF8 encoded docuement (only trying one for now to test...) thanks for any assistance.
- (void)submitPackageJSONv3:(NSDictionary*)json document:(NSData*)document {
    
    // prepare multipart boundary
    NSString *boundary = @"unique-consistent-string";
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
    
    // ---- initialize request object ----
    NSMutableURLRequest *request =
    [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"https://sandbox.esignlive.com/api/packages"]];
    [request setHTTPMethod:@"POST"];
    
    // ---- set headers ----
    [request setValue:@"Basic enVyZ........................4b0U4Tw==" forHTTPHeaderField: @"Authorization"];
    [request setValue:@"gzip, deflate" forHTTPHeaderField: @"Accept-Encoding"];
    [request setValue:@"*/*" forHTTPHeaderField: @"Accept"];
    [request setValue:@"keep-alive" forHTTPHeaderField: @"Connection"];
    [request setValue:@"chunked" forHTTPHeaderField: @"Transfer-Encodinge"];
    [request setValue:contentType forHTTPHeaderField: @"Content-Type"];
    
    NSMutableData *body = [NSMutableData data];
    
    // ---- apppend JSON ----
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"%@\r\n", @"Content-Disposition: form-data; name='payload'"]
                      dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[NSKeyedArchiver archivedDataWithRootObject:json]];
    
    
    // ---- apppend docs ----
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"%@\r\n", @"Content-Disposition: form-data; name='file'; filename='file'"]
                      dataUsingEncoding:NSUTF8StringEncoding]];
    
    [body appendData:document];
    [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    
    // ---- set HTTP Body ----
    [request setHTTPBody:body];
    
    // ---- set the content-length header ----
    NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[body length]];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    
    // ---- send HTTP POST ----
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
        NSLog(@"%@", error.description);
        if(data.length > 0)
        {
            //success
           NSLog(@"Success");
        }
    }];
}

rdediana | Posts: 23

Reply to: REST - POST Package JSON + Documents Assistance

0 votes
slight modification: receiving the below error.
2016-06-18 17:11:04.533 ESLRemoteExpert[82361:18662663] {"messageKey":"error.internal.default","technical":"65533","message":"Unexpected Error. Our technical staff have been notified and will look into the problem. We apologize for any inconvenience this may have caused you.","code":500,"name":"Unhandled Server Error"}
i suspect this is a file encoding issue. ? any suggestions would be greatly appreciated.
- (void)submitPackageJSONv5:(NSDictionary*)json documentPath:(NSString*)documentPath {
    
    // prepare multipart boundary
    NSString *boundary = @"unique-consistent-string";
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
    
    // ---- initialize request object ----
    NSMutableURLRequest *request =
    [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"https://sandbox.esignlive.com/api/packages"]];
    [request setHTTPMethod:@"POST"];
    
    // ---- set headers ----
    [request setValue:@"Basic enVyZ1A3Yl....................YTV1eW94b0U4Tw==" forHTTPHeaderField: @"Authorization"];
    [request setValue:@"gzip, deflate" forHTTPHeaderField: @"Accept-Encoding"];
    [request setValue:@"*/*" forHTTPHeaderField: @"Accept"];
    [request setValue:@"keep-alive" forHTTPHeaderField: @"Connection"];
    [request setValue:@"chunked" forHTTPHeaderField: @"Transfer-Encodinge"];
    [request setValue:contentType forHTTPHeaderField: @"Content-Type"];

    NSMutableData *body = [NSMutableData data];

    // ---- apppend JSON ----
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"%@\r\n", @"Content-Disposition: form-data; name='payload'"]
                      dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[NSKeyedArchiver archivedDataWithRootObject:json]];

    NSData *filedata = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:documentPath]];
    NSLog(@"file:%@",filedata);

    // ---- apppend docs ----
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"%@\r\n", @"Content-Disposition: form-data; name='file'; filename='file'"]
                      dataUsingEncoding:NSUTF8StringEncoding]];
   // [body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:filedata];
    
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [request setHTTPBody:body];

    NSHTTPURLResponse* response =[[NSHTTPURLResponse alloc] init];
    NSError* error = [[NSError alloc] init] ;
    
    error = [NSError errorWithDomain:DGErrorDomain code:DGFNIDParsingFailedError userInfo:nil];

    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    
    if (error)
    {
       NSLog(@"%@", error.description);
        
    }

    NSString *responseString = [[NSString alloc] initWithBytes:[responseData bytes]
                                                         length:[responseData length]
                                                       encoding:NSUTF8StringEncoding];
    NSLog(@"%@", responseString);
    
}

rdediana | Posts: 23

Reply to: REST - POST Package JSON + Documents Assistance

0 votes
hey Team, Any way to identify the issue behind this message;
2016-06-18 17:11:04.533 ESLRemoteExpert[82361:18662663] {"messageKey":"error.internal.default","technical":"65533","message":"Unexpected Error. Our technical staff have been notified and will look into the problem. We apologize for any inconvenience this may have caused you.","code":500,"name":"Unhandled Server Error"}
potentially viewing the server logs?

mwilliams | Posts: 957

Reply to: REST - POST Package JSON + Documents Assistance

0 votes
Have you tried a more basic call? Like just changing the status of a SENT package to DRAFT? Just want to make sure you can successfully make a call to ESL with the REST API from your objective c code. I would guess the problem is an issue with the JSON payload. Unfortunately, I don't have an objectivec test environment on my Windows machine. I will look into an objective c IDE/compiler for Windows to see if I can actually test this out, myself.

rdediana | Posts: 23

Reply to: REST - POST Package JSON + Documents Assistance

0 votes
Hello Michael, just tried the bellow request, which completed successfully.
- (void)getRequest {
    
    // 1
    NSURL *url = [NSURL URLWithString:@"https://sandbox.esignlive.com/api/packages"];
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
    
    // 2
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
    request.HTTPMethod = @"GET";
    [request setValue:@"Basic enVyZ1A3Y...................94b0U4Tw==" forHTTPHeaderField: @"Authorization"];
    // 3
    
    NSError *error = nil;
    
    if (!error) {
        // 4
        NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
        }];
        
        // 5
        [dataTask resume];
    }
    
}

rdediana | Posts: 23

Reply to: REST - POST Package JSON + Documents Assistance

0 votes
curious. to simply the requirements, can i host the documents in a template within ESL and reference this template when creating a new package. ? i could still submit JSON data for role and package attributes, and simply reference pre-positioned documents hosting on the ESL server / cloud? if yes, could you provide some guidance on how to create a new package, which submits the role / package details via JSON REST API, while referencing the template for document requirements. . thanks for any assistance. regards,

rdediana | Posts: 23

Reply to: REST - POST Package JSON + Documents Assistance

0 votes
this looks great! i'll review more closely now, and post any questions i may have. in terms of the sample app, i would appreciate anything can post ore share. if you could kindly provide the URL once it's available. regards, Regan

mwilliams | Posts: 957

Reply to: REST - POST Package JSON + Documents Assistance

0 votes
Uploaded and available from the code share: https://developer.esignlive.com/code-share/create-package-rest-objective-c/

Hello! Looks like you're enjoying the discussion, but haven't signed up for an account.

When you create an account, we remember exactly what you've read, so you always come right back where you left off