MrJoshFisher MrJoshFisher - 3 months ago 8
JSON Question

How do I use a forward slash in my api call?

Hello all Im starting to use APIs for development purposes and ive come accross and api call that uses / as a means of separating values I've been putting ?

var requestURL = 'https://alpha.openaddressesuk.org/addresses.json?';

$.getJSON(requestURL, {
'street' : street,
'town' : town,
'postcode' : postcode,
}, function(data) {


the result of the requesturl would be https://alpha.openaddressesuk.org/addresses.json?street=STREET?town=TOWN?postcode=POSTCODE

but I've noticed that some apis have / instead of ? in the request URL

So how would I do this

var requestURL = 'http://transportapi.com/v3/uk/train/station/{{STATIONNAME}}/{{STATION DATE}}/{{STATION TIME}}/timetable.json?app_id=APPID&app_key=APIKEY&train_status=passenger';

$.getJSON(requestURL, {
'stationname' : stationname,
'date' : date,
'time' : time,
}, function(data) {
console.log(data)
}


but wouldn't that put ? in-between each parameter?

Tim Tim
Answer

Use Percent encoding on the station name to change the / into %2F. Full details here: https://en.wikipedia.org/wiki/Percent-encoding

In javascript this can be achieved using encodeURIComponent(str); eg

// Build request URL (assumes date and time are strings in the
// correct format)
var requestURL = 
    'http://transportapi.com/v3/uk/train/station/' + 
    encodeURIComponent(stationname) + '/' + date + '/' + 
    time + '/timetable.json';

$.getJSON(requestURL, {
    'app_id': app_id,
    'app_key': app_key,
    'train_status': 'passenger',
}, function(data) {
        console.log(data)
}
Comments