Having trouble with missing quotes in Swift when making a REST POST request

Struggling with a seemingly simple REST call that has left me completely stuck. I have a node-based restful service that requires an array of strings as input. However, every time I make the call with what seems like a valid parameter, the server throws an error indicating it's trying to interpret the string as an integer. This leads me to believe that somewhere along the line, the quotes around the string are being lost.

Below is the original Swift (3) code snippet along with two additional variants at the end. The function takes in "id" and "parmvalue" as parameters:

let url = URL(string: "\(root)path/\(id)/myendpoint")
var request = URLRequest(url:url!)
request.httpMethod = "POST"
request.addValue("application/json",forHTTPHeaderField: "Content-Type")
let params = [ "parm" : [ parmvalue ] ]
do {
    let jsonParams = try JSONSerialization.data(withJSONObject: params)
    request.httpBody = jsonParams
    let task = URLSession.shared.dataTask(with: request, completionHandler: {(data, response, error) -> Void in
...etc

On the server side, here's the corresponding code snippet:

    app.post('/path/:id/myendpoint', globals.authentication, function(req, res){
        var param = JSON.parse(req.param('parm', "[]"));
        var Id = req.param('id', -1);
...etc

When passing in a parmvalue = "898e1ac8-4892-4e6e-89cb-4b2ea9306f75.jpg", the server responds with a 500 error, and the data received by the completionHandler for the dataTask shows:

SyntaxError: Unexpected token e

This error occurs right at the line where "var param" is defined. The unexpected token usually corresponds to the first non-numeric value in the guid.

Variant 1 attempted to hardcode the JSON:

let url = URL(string: "\(root)path/\(id)/myendpoint")
var request = URLRequest(url:url!)
request.httpMethod = "POST"
request.addValue("application/json",forHTTPHeaderField: "Content-Type")
let testparamsString = "{ \"photos\" : [ \"\(filename)\" ] }"
let testparams = testparamsString.data(using: .utf8)
request.httpBody = testparams
...etc

Variant 2 tried using query param format if JSON didn't work:

let url = URL(string: "\(root)path/\(id)/myendpoint")
var request = URLRequest(url:url!)
request.httpMethod = "POST"
let queryparams = "parm[]=\(filename.stringByAddingPercentEncodingForFormUrlencoded()!)"
request.httpBody = queryparams.data(using: .utf8)

Note that variable names and values have been anonymized in the code snippets provided. All three variations in Swift resulted in the same response from the server, suggesting any issues aren't due to manual anonymizing.

Just for reference, here's a snippet from a C# application that successfully calls this endpoint using the RestSharp library:

var request = new RestRequest($"/path/{id}/myendpoint", Method.POST);
var parmArray = new JArray();
parmArray.Add(parmvalue);
var jsonParms = JsonConvert.SerializeObject(parmArray, Formatting.None);
request.AddParameter("parm", jsonParms);

Answer â„–1

Variant 2 came very close, but a crucial extra backslash was needed to preserve the quotes. This is the revised code that successfully accomplishes that:

    let link = URL(string: "\(root)path/\(id)/destination")
    var req = URLRequest(url:link!)
    req.httpMethod = "POST"
    req.addValue("application/json",forHTTPHeaderField: "Content-Type")
    let parametersStr = "{ \"images\" : \"[\\\"\(picName)\\\"]\" }"
    req.httpBody = parametersStr.data(using: .utf8)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Spring Boot's global exception handler fails to catch HttpMessageNotReadableException

My exception handler successfully captures exceptions thrown from my controller, service layer, or repository layer. However, it fails to catch exceptions occurring before entering the controller. Specifically, when a malformed JSON body is passed to a POS ...

accessing all records through a RESTful API

I have a unique question regarding REST API pagination. I have written a script to extract specific data from this page: import requests import json import pandas as pd url = 'http://data.rcsb.org/rest/v1/core/entry/5XTI' r = requests.get(url) ...

"Discrepancy in results between JSON stringify and JavaScript object conversion

I need to save this object in a database, but first I have to send it to the backend. Recorder {config: Object, recording: false, callbacks: Object, context: AudioContext, node: ScriptProcessorNode…} However, after using JSON.stringify(recorder) The r ...

I am looking to display a single column in a SQL query as a JSON array containing all the child values

My query involves retrieving various fields from a product table and also assigning multiple tags to each product using a ProductTagMapping table. I want to include a Tags column in my output that contains a JSON Array of the associated Tag Names from a Pr ...

Transmitting an Array in JSON Format using PHP (Campaign Monitor)

Hey there, I have this interesting JSON Array called sample.txt. It's obtained from a sweepstakes form that collects user details like name and email. The WooBox sends the JSON Array with information for each entry. In this case, we have two entries w ...

Having difficulty with Angular's ng-options feature in a Select element

I'm currently tackling an issue with using ng-options to iterate through an array of objects and display specific properties in a select element. Upon querying the api/admin endpoint, I receive JSON data containing details of all users holding the ad ...

Delete a particular item from a JSON object in real-time using TypeScript/JavaScript

Upon examining the JSON data provided, it contains a node called careerLevels which includes inner child elements. input = { "careerLevelGroups": [ { "201801": 58, "201802": 74, ...

Exploring the depths of asynchronous calls in AngularJS with nested functions

Currently, I'm tackling a small project with AngularJS and finding myself tangled in multiple asynchronous calls that are starting to become chaotic. I know there must be a more efficient way to handle these calls, but I'm unsure of the best appr ...

Obtain log records in Azure and save them as a JSON object

Is there a recommended method to export logs from Azure in JSON format and what are the best practices for doing so? While using direct Kusto queries to export logs to CSV is an option, unfortunately there is no built-in option for exporting logs in JSON ...

Convert data in JavaScript and send it as a string in PHP

I'm currently facing a small issue with my JavaScript code. Specifically, I am using AJAX and attempting to retrieve a variable in PHP. Everything seems to be working fine except for the "param" data. Below is the snippet of my code: $('#sign ...

Counting duplicate values associated with the same key in a JSON array using JavaScript/NodeJS

Hello everyone, I could really use some assistance in solving this issue. If this has already been asked before, please direct me to the original question. Currently, I am working with a JSON array of elements. For example: var data = [{"key":"Item1"},{ ...

Arranging JSON based on values in an array using node.js

Seeking assistance with sorting a JSON object by specific keys within a node.js program. The task involves arranging the object in ascending order based on the "trip_miles" value when the "trip_name" equals CC, and then extracting only the id's as out ...

Converting a DataTable into a nested JSON structure using C#

I need help converting a DataTable to nested JSON. My table, named Announcement, has the following columns: Category, Headline, Details, Short_desc, Author, and Display_date. The DataTable results look like this: Category Headline Details Shor ...

Guide on retrieving information from Spark and showcasing it through Angular

Trying to navigate the world of Spark framework and AngularJS as a beginner, I set out to create a basic REST application. However, I hit a roadblock when it came to retrieving data from the server and displaying it using Angular. My initial task was simp ...

Encountering problems while trying to upload JSON data to the database - receiving a "301 Moved Permanently

Currently working on a Symfony webservice and encountering an issue while making a POST call to the database. When using Postman for the POST request, I am receiving an error 301 - moved permanently. See below the controller code: /** * @Route("/post/inf ...

When trying to parse a JSON response on a NodeJS server, it returns as

Having trouble accessing a JSON object in a node.js server? Here's my situation - I am trying to retrieve data from a database and parse the JSON response, but when I try to access a specific key, it returns undefined. How can I successfully access th ...

What is the best way to calculate the frequency of certain words in my data using Hive?

I'm working with a table of JSON formatted Twitter objects in Hive, with n rows and 1 column. My task is to count the frequency of words like 'hon' and 'han' within different objects (each object contains a 'text' attribu ...

Transmitting several images via the HTML INPUT tag through AJAX to a Laravel Controller, in addition to sending other data not contained within the

$('#update-post').on('click', function(event){ $.ajax({ method: 'POST', url: editPostUrl, data: { content: $('#post-content').val(), deleteImages: deleteImages, postId: postID, ...

Sending an object along with additional variables back to the client through JSON serialization: Tips and Tricks

What is the best way to incorporate the dictionary a into the response, and how can I retrieve two objects through an ajax call? view def abc(request): cp = Cp.objects.get(id=1) cp = serializers.serialize('json', [cp,]) cp = json.lo ...

Utilizing a combination of ORMLite, JSON, and foreign objects revolution

Consider a scenario where we have a basic ORMLite data model (with annotations) in an Android App: A { String id; } B { String id; A A_id; } If we are receiving objects from a PostgreSQL external database where A_id is stored as a String, how ...