Error when I generate a string that gets passed into the body of my matrix request

in python, I am trying to generate a string that gets passed into the body of my request. I have confirmed the headers are correct.

for example:

ORSbody = '{"locations":['+locations+'],"metrics":["distance","duration"]}'
ORSbody
ORSResponse = requests.post('https://api.openrouteservice.org/v2/matrix/driving-hgv', json=ORSbody, headers=ORSheaders)

print(ORSbody) returns this:

{"locations":[[-101.70934,34.184501],[-101.84204,33.738393],[-101.7496,34.1873],[-101.841254,33.593317],[-101.835259,32.970953],[-101.839031,33.641593],[-101.94001,33.641702],[-101.808573,33.527775]],"metrics":["distance","duration"]}

When I compare this format to the format of the example they match up perfectly. But when I pass my variable(ORSbody) into the body parameter I get a 400 level error.

But I can run the code below and receive a 200 response from the server. all I did was paste the generated string into the variable set statement

ORSbody = {"locations":[[-101.70934,34.184501],[-101.84204,33.738393],[-101.7496,34.1873],[-101.841254,33.593317],[-101.835259,32.970953],[-101.839031,33.641593],[-101.94001,33.641702],[-101.808573,33.527775]],"metrics":["distance","duration"]}
ORSResponse = requests.post('https://api.openrouteservice.org/v2/matrix/driving-hgv', json=ORSbody, headers=ORSheaders)

It doesnt make any sense to me because the string I generate in the first code block is the exact same string that the variable gets set to in the second code block.

Can any one advise on what I am doing wrong. I tried converting my string into a dictionary but the format came out completely wrong to the example on ORS website.

Hi @mbrantley94,

the json argument always takes an object. if you want to pass a string, use data (see this stackoverflow answer).

You could also just use our python package openrouteservice-py.

Best regards

1 Like

I was able to get it to work thanks to the stackoverflow answer you provided. I read the documentation for the ORS module but since its lacking an example, it left my a little confused. The description has clients as a parameter but the parameters list doesn’t include client in it. is there a place where I can find more detailed documentation for the module? lastly, thank you for your time and help.

I’ve just had a look at that rtd page and there are quite some outdated parts.
You would normally use that function through the client.distancce_matrix.
There are some examples in the GitHub Readme.
But the most detailed documentation is the code itself :grimacing:.
Best just take a look inside the classes you want to use.

Best regards

1 Like