How to make an HTTP get request with parameters
In a GET request, you pass parameters as part of the query string.
string url = "http://somesite.com?var=12345";
GET request with parameters
Example how to use URLQueryItem
for the requests.
func getRequest(params: [String:String]) {
let urlComp = NSURLComponents(string: "https://my-side.com/data")!
var items = [URLQueryItem]()
for (key,value) in params {
items.append(URLQueryItem(name: key, value: value))
}
items = items.filter{!$0.name.isEmpty}
if !items.isEmpty {
urlComp.queryItems = items
}
var urlRequest = URLRequest(url: urlComp.url!)
urlRequest.httpMethod = "GET"
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let task = session.dataTask(with: urlRequest, completionHandler: { (data, response, error) in
})
task.resume()
}
getRequest(params: ["token": "AS7F87SAD84889AD"])
Python Requests - pass parameter via GET
Here's the relevant code to perform a GET http call from the official documentation
import requests
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.get('http://httpbin.org/get', params=payload)
In order to adapt it to your specific request:
import requests
payload = {'q': 'food'}
r = requests.get('http://httpbin.org/get', params=payload)
print (r.text)
Here's the obtained result if I run the 2nd example:
python request_test.py
{"args":{"q":"food"},"headers":{"Accept":"*/*","Accept-Encoding":"gzip, deflate","Connection":"close","Host":"httpbin.org","User-Agent":"python-requests/2.18.1"},"origin":"x.y.z.a","url":"http://httpbin.org/get?q=food"}
How are parameters sent in an HTTP POST request?
The values are sent in the request body, in the format that the content type specifies.
Usually the content type is application/x-www-form-urlencoded
, so the request body uses the same format as the query string:
parameter=value&also=another
When you use a file upload in the form, you use the multipart/form-data
encoding instead, which has a different format. It's more complicated, but you usually don't need to care what it looks like, so I won't show an example, but it can be good to know that it exists.
Setting query string using Fetch GET request
Update March 2017:
URL.searchParams support has officially landed in Chrome 51, but other browsers still require a polyfill.
The official way to work with query parameters is just to add them onto the URL. From the spec, this is an example:
var url = new URL("https://geo.example.org/api"),
params = {lat:35.696233, long:139.570431}
Object.keys(params).forEach(key => url.searchParams.append(key, params[key]))
fetch(url).then(/* … */)
However, I'm not sure Chrome supports the searchParams
property of a URL (at the time of writing) so you might want to either use a third party library or roll-your-own solution.
Update April 2018:
With the use of URLSearchParams constructor you could assign a 2D array or a object and just assign that to the url.search
instead of looping over all keys and append them
var url = new URL('https://sl.se')
var params = {lat:35.696233, long:139.570431} // or:
var params = [['lat', '35.696233'], ['long', '139.570431']]
url.search = new URLSearchParams(params).toString();
fetch(url)
Sidenote: URLSearchParams
is also available in NodeJS
const { URL, URLSearchParams } = require('url');
Swift GET request with parameters
When building a GET
request, there is no body to the request, but rather everything goes on the URL. To build a URL (and properly percent escaping it), you can also use URLComponents
.
var url = URLComponents(string: "https://www.google.com/search/")!
url.queryItems = [
URLQueryItem(name: "q", value: "War & Peace")
]
The only trick is that most web services need +
character percent escaped (because they'll interpret that as a space character as dictated by the application/x-www-form-urlencoded
specification). But URLComponents
will not percent escape it. Apple contends that +
is a valid character in a query and therefore shouldn't be escaped. Technically, they are correct, that it is allowed in a query of a URI, but it has a special meaning in application/x-www-form-urlencoded
requests and really should not be passed unescaped.
Apple acknowledges that we have to percent escaping the +
characters, but advises that we do it manually:
var url = URLComponents(string: "https://www.wolframalpha.com/input/")!
url.queryItems = [
URLQueryItem(name: "i", value: "1+2")
]
url.percentEncodedQuery = url.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B")
This is an inelegant work-around, but it works, and is what Apple advises if your queries may include a +
character and you have a server that interprets them as spaces.
So, combining that with your sendRequest
routine, you end up with something like:
func sendRequest(_ url: String, parameters: [String: String], completion: @escaping ([String: Any]?, Error?) -> Void) {
var components = URLComponents(string: url)!
components.queryItems = parameters.map { (key, value) in
URLQueryItem(name: key, value: value)
}
components.percentEncodedQuery = components.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B")
let request = URLRequest(url: components.url!)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard
let data = data, // is there data
let response = response as? HTTPURLResponse, // is there HTTP response
200 ..< 300 ~= response.statusCode, // is statusCode 2XX
error == nil // was there no error
else {
completion(nil, error)
return
}
let responseObject = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any]
completion(responseObject, nil)
}
task.resume()
}
And you'd call it like:
sendRequest("someurl", parameters: ["foo": "bar"]) { responseObject, error in
guard let responseObject = responseObject, error == nil else {
print(error ?? "Unknown error")
return
}
// use `responseObject` here
}
Personally, I'd use JSONDecoder
nowadays and return a custom struct
rather than a dictionary, but that's not really relevant here. Hopefully this illustrates the basic idea of how to percent encode the parameters into the URL of a GET request.
See previous revision of this answer for Swift 2 and manual percent escaping renditions.
How do you add query parameters to a Dart http request?
You'll want to construct a Uri
and use that for the request. Something like
final queryParameters = {
'param1': 'one',
'param2': 'two',
};
final uri =
Uri.https('www.myurl.com', '/api/v1/test/${widget.pk}', queryParameters);
final response = await http.get(uri, headers: {
HttpHeaders.authorizationHeader: 'Token $token',
HttpHeaders.contentTypeHeader: 'application/json',
});
See https://api.dartlang.org/stable/2.0.0/dart-core/Uri/Uri.https.html
Related Topics
Swift Access to Variable Length Array
Show Nsmenu Only on Nsstatusbarbutton Right Click
Is There a Daylight Savings Check in Swift
Xcode 11 Beta 3, Build Error "Unknown Attribute 'State'", "Use of Undeclared Type 'View'" etc
Sktextureatlas No Longer Sharing Textures in iOS 10
What Is the Use of the Validate() Method in Alamofire.Request
Avcapturevideodataoutput Captureoutput Not Being Called
Play Local Audio File with Avaudioplayer
Function That Takes a Protocol and a Conforming Class (!) Instance as Parameters
How to Generate Random Numbers Without Repetition in Swift
How to Rotate Sprites Around a Joint
Uitextview Change Text Color of Specific Text
Modal View Closes When Selecting an Image in Uiwebview iOS
Swift/Firebase - Sort Posts in Tableview by Date
How to Embed Third Party Framework on Ionic Capacitor Custom Plugin
How to Request a Desktop Version of a Webpage Using Uiwebview in Swift 3.0