Search ¶
Setup ¶
Search entry point ¶
URL: |
|
Example ¶
These are complete working examples in several different languages, showing how to use the REST API search. You can try them right now.
Linux terminal / Windows command prompt:
curl
"https://search.magiclaneapis.com/v1"
-X
POST
-H
"Content-Type:
application/json"
-H
"Authorization:
YOUR_API_KEY_TOKEN"
-d
@payload.json
Linux note - do not use @~/payload.json instead of
@/home/user/payload.json
because
~
does not resolve due to the
@
;
use only relative path
@payload.json
or absolute path
@/home/user/payload.json
where
payload.json
is a text file containing the following:
complete minimal
payload.json
file -
search
type
,
text
to search for (query),
target
list what to search for, in the case of POIs - also specify POI categories with
poi_categs
,
ref_location
a reference location in longitude and latitude around which to search;
debug
true causes resulting json to be pretty printed;
note that, although the
target
field and the
poi_categs
field can be omitted -
in that case the search looks only for settlements (villages, towns, cities), regions, countries
1{
2 "text": "rest",
3 "target": ["pois", "addresses"],
4 "poi_categs": ["food&drink"],
5 "ref_location": [4.89352, 52.36597],
6 "debug": true
7}
complete
payload.json
file -
all default values shown explicitly
- this json request is equivalent to, and produces the same output as, the previous json request above;
1{
2 "type": "free_text",
3 "text": "rest",
4 "target": ["pois", "addresses"],
5 "poi_categs": ["food&drink"],
6 "ref_location": [4.89352, 52.36597],
7 "max_results": 15,
8 "exact_match": false,
9 "fuzzy": false,
10 "estimate_hno": true,
11 "debug": true,
12 "locale": "en"
13}
complete minimal
python search request -
search
type
,
text
to search for (query),
target
list what to search for, in the case of POIs - also specify POI categories with
poi_categs
,
ref_location
a reference location in longitude and latitude around which to search;
debug
true causes resulting json to be pretty printed;
note that the
debug
parameter is omitted, as the json is stored in the response variable, not printed
directly, so formatting the json output is done locally by the
json.dumps()
function instead;
1import requests
2import json
3
4url = "https://search.magiclaneapis.com/v1"
5headers = {"Content-Type": "application/json", "Authorization": "YOUR_API_KEY_TOKEN" }
6payload = {
7 "text": "rest",
8 "target": ["pois", "addresses"],
9 "poi_categs": ["food&drink"],
10 "ref_location": [4.89352, 52.36597]
11}
12response = requests.post(url, json=payload, headers=headers)
13r = response.json()
14print(json.dumps(r, indent=3))
search request with all default values shown explicitly - this json request is equivalent to, and produces the same output as, the previous json request above;
note that in python,
True
and
False
are case-sensitive;
the json module is part of python, but the requests module may need to be installed (linux terminal:
pip
install
requests
)
1import requests
2import json
3url = "https://search.magiclaneapis.com/v1"
4headers = {"Content-Type": "application/json", "Authorization": "YOUR_API_KEY_TOKEN" }
5payload = {
6 "type": "free_text",
7 "text": "rest",
8 "target": ["pois", "addresses"],
9 "poi_categs": ["food&drink"],
10 "ref_location": [4.89352, 52.36597],
11 "max_results": 15,
12 "exact_match": False,
13 "fuzzy": False,
14 "estimate_hno": True,
15 "debug": True,
16 "locale": "en"
17}
18response = requests.post(url, json=payload, headers=headers)
19r = response.json()
20print(json.dumps(r, indent=3))
This C example uses
libcurl
which can be installed on Linux (debian/ubuntu flavors), for example, like this:
sudo
apt
install
libcurl4-gnutls-dev
Save the following code in a text file named
search.c
using your favorite text editor, such as
vi
or
geany
,
without the line numbers, those are only for reference:
complete search request in
C
with
all default values shown explicitly
-
search
type
,
text
to search for (query),
target
list what to search for, in the case of POIs - also specify POI categories with
poi_categs
,
ref_location
a reference location in longitude and latitude around which to search;
debug
true causes resulting json to be pretty printed;
1#include <curl/curl.h>
2
3int main (int argc, char *argv[])
4{
5 CURL *curl;
6 CURLcode res;
7
8 curl_global_init(CURL_GLOBAL_ALL);
9 curl = curl_easy_init();
10 if (curl == NULL) { return 128; }
11
12 char* jsonObj = "{"
13 "\"type\": \"free_text\","
14 "\"text\": \"rest\","
15 "\"target\": [\"pois\",\"addresses\"],"
16 "\"poi_categs\": [\"food&drink\"],"
17 "\"ref_location\": [4.89352, 52.36597],"
18 "\"max_results\": 15,"
19 "\"exact_match\": false,"
20 "\"fuzzy\": false,"
21 "\"estimate_hno\": true,"
22 "\"debug\": true,"
23 "\"locale\": \"en\""
24 "}";
25 struct curl_slist *headers = NULL;
26 curl_slist_append(headers, "Content-Type: application/json");
27 curl_slist_append(headers, "Authorization: YOUR_API_KEY_TOKEN");
28
29 curl_easy_setopt(curl, CURLOPT_URL, "https://search.magiclaneapis.com/v1");
30 curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "PUT");
31 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
32 curl_easy_setopt(curl, CURLOPT_POSTFIELDS, jsonObj);
33
34 res = curl_easy_perform(curl);
35
36 curl_easy_cleanup(curl);
37 curl_global_cleanup();
38 return res;
39}
Compile the program - for example, on Linux, at the terminal/command prompt type:
gcc
search.c
-lcurl
-o
search
A binary executable named
search
is created which can be run like this to
send the JSON POST request to the REST API endpoint, receive, and print the response:
./search
To install D on Linux (debian/ubuntu flavors), at a terminal/command prompt type:
sudo
apt
install
gdc
D can be downloaded for other platforms from this link
complete search request in
D
with
all default values shown explicitly
-
search
type
,
text
to search for (query),
target
list what to search for, in the case of POIs - also specify POI categories with
poi_categs
,
ref_location
a reference location in longitude and latitude around which to search;
debug
true causes resulting json to be pretty printed;
copy and paste this code in a text file
named
search.d
, without the line numbers - those are for reference:
1import std.stdio;
2import std.net.curl;
3void main()
4{
5 string payload = '{
6 "type": "free_text",
7 "text": "rest",
8 "target": ["pois", "addresses"],
9 "poi_categs": ["food&drink"],
10 "ref_location": [4.89352, 52.36597],
11 "max_results": 15,
12 "exact_match": false,
13 "fuzzy": false,
14 "estimate_hno": true,
15 "debug": true,
16 "locale": "en"
17 }';
18 auto http = HTTP();
19 http.addRequestHeader("Content-Type", "application/json");
20 http.addRequestHeader("Authorization", "YOUR_API_KEY_TOKEN");
21 auto content = post("https://search.magiclaneapis.com/v1", payload, http);
22 writeln(content);
23}
Compile the program - for example, on Linux, at the terminal/command prompt type:
gdc
search.d
-o
search
A binary executable named
search
is created which can be run like this to
send the JSON POST request to the REST API endpoint, receive, and print the response:
./search
To install Julia on Linux (debian/ubuntu flavors), at a terminal/command prompt type:
sudo
apt
install
julia
Julia can be downloaded for other platforms from this link
To start Julia, type:
julia
To install the JSON and HTTP packages, at the Julia prompt type:
import
Pkg;
Pkg.add("JSON");
Pkg.add("HTTP")
complete search request in
Julia
with
all default values shown explicitly
-
search
type
,
text
to search for (query),
target
list what to search for, in the case of POIs - also specify POI categories with
poi_categs
,
ref_location
a reference location in longitude and latitude around which to search;
debug
true causes resulting json to be pretty printed;
copy and paste this code at the Julia prompt, without the line numbers - those are for reference:
1using JSON, HTTP
2req = """{
3 "type": "free_text",
4 "text": "rest",
5 "target": ["pois", "addresses"],
6 "poi_categs": ["food&drink"],
7 "ref_location": [4.89352, 52.36597],
8 "max_results": 15,
9 "exact_match": false,
10 "fuzzy": false,
11 "estimate_hno": true,
12 "debug": true,
13 "locale": "en"
14 }"""
15ans = HTTP.request("POST", "https://search.magiclaneapis.com/v1",
16 ["Content-Type" => "application/json",
17 "Authorization" => "YOUR_API_KEY_TOKEN"], req);
18str = String(ans.body);
19print(str)
The free IntelliJ IDEA Community Edition IDE can be downloaded from this link
Create a new
kotlin
project in IntelliJ.
In your new kotlin project, browse to
src
->
main
->
kotlin
->
Main.kt
Delete all the code in
Main.kt
and replace it with the kotlin search request code shown below:
(without the line numbers - those are only for reference)
complete search request in
kotlin
with
all default values shown explicitly
-
search
type
,
text
to search for (query),
target
list what to search for, in the case of POIs - also specify POI categories with
poi_categs
,
ref_location
a reference location in longitude and latitude around which to search;
debug
true causes resulting json to be pretty printed;
1package kot.search.post
2
3import java.net.URI
4import java.net.http.HttpClient
5import java.net.http.HttpRequest
6import java.net.http.HttpResponse
7
8fun main()
9{
10 val request: String = """
11 {
12 "type": "free_text",
13 "text": "rest",
14 "target": ["pois", "addresses"],
15 "poi_categs": ["food&drink"],
16 "ref_location": [4.89352, 52.36597],
17 "max_results": 15,
18 "exact_match": false,
19 "fuzzy": false,
20 "estimate_hno": true,
21 "debug": true,
22 "locale": "en"
23 }"""
24 print(request)
25 val client = HttpClient.newBuilder().build();
26 val postrequest = HttpRequest.newBuilder()
27 .uri(URI.create("https://search.magiclaneapis.com/v1"))
28 .header("Content-Type", "application/json")
29 .header("Authorization", "YOUR_API_KEY_TOKEN")
30 .POST(HttpRequest.BodyPublishers.ofString(request))
31 .build()
32 val response = client.send(postrequest, HttpResponse.BodyHandlers.ofString());
33 println(response.statusCode())
34 println(response.body())
35}
kotlin
search request!
File->Project
Structure
and in the left panel select
Modules
and then in the right panel select the
Dependencies
tab and make sure the
[x]
KotlinJavaRuntime
box is checked, then click Apply and OK,
and run the example again.
The free IntelliJ IDEA Community Edition IDE can be downloaded from this link
Create a new
groovy
project in IntelliJ.
In your new groovy project, browse to
src
->
Main.groovy
Delete all the code in
Main.groovy
and replace it with the groovy search request code shown below:
(without the line numbers - those are only for reference)
complete search request in
groovy
with
all default values shown explicitly
-
search
type
,
text
to search for (query),
target
list what to search for, in the case of POIs - also specify POI categories with
poi_categs
,
ref_location
a reference location in longitude and latitude around which to search;
debug
true causes resulting json to be pretty printed;
1static void main(String[] args)
2{
3 def post = new URL("https://search.magiclaneapis.com/v1").openConnection();
4 def message = '''
5 {
6 "type": "free_text",
7 "text": "rest",
8 "target": ["pois", "addresses"],
9 "poi_categs": ["food&drink"],
10 "ref_location": [4.89352, 52.36597],
11 "max_results": 15,
12 "exact_match": false,
13 "fuzzy": false,
14 "estimate_hno": true,
15 "debug": true,
16 "locale": "en"
17 }
18 '''
19 post.setRequestMethod("POST")
20 post.setDoOutput(true)
21 post.setRequestProperty("Content-Type", "application/json")
22 post.setRequestProperty("Authorization", "YOUR_API_KEY_TOKEN")
23 post.getOutputStream().write(message.getBytes("UTF-8"));
24 def postRC = post.getResponseCode();
25 println(postRC);
26 if (postRC.equals(200)) {
27 println(post.getInputStream().getText());
28 }
29}
groovy
search request!
The free IntelliJ IDEA Community Edition IDE can be downloaded from this link
Create a new
scala
project in IntelliJ.
If Language: Scala is not listed in the create new project dialog, click on + to the right
of the listed languages and select
Scala
to install the plugin, then restart intellij,
create a new project and select Language: Scala.
In your new scala project, browse to the
build.sbt
file and add this line:
libraryDependencies
+=
"org.scalaj"
%
"scalaj-http_2.13"
%
"2.4.2"
Note - at the time of this writing, the latest scala version is
2.13
;
the
scalaVersion
you see in build.sbt must match the
scalaj-http_2.13
version;
if the
scalaVersion
you see in build.sbt is newer than
2.13
,
such as 2.18 for example, then go to
https://mvnrepository.com/artifact/org.scalaj/scalaj-http
to see the latest scalaj-http_2.18 version, such as 2.5.6 for example, and replace 2.4.2 with that version, as well as scalaj-http_2.13 with scalaj-http_2.18
A notification button appears within the window to the right -
Load
sbt
Changes
-
click this floating button
to update.
In your new scala project, browse to
src
->
Main.scala
Delete all the code in
Main.scala
and replace it with the scala search request code shown below:
(without the line numbers - those are only for reference)
complete search request in
scala
with
all default values shown explicitly
-
search
type
,
text
to search for (query),
target
list what to search for, in the case of POIs - also specify POI categories with
poi_categs
,
ref_location
a reference location in longitude and latitude around which to search;
debug
true causes resulting json to be pretty printed;
1import scalaj.http.{Http, HttpOptions}
2object Main
3{
4 def main(args: Array[String]): Unit =
5 {
6 val request = s"""
7 {
8 "type": "free_text",
9 "text": "rest",
10 "target": ["pois", "addresses"],
11 "poi_categs": ["food&drink"],
12 "ref_location": [4.89352, 52.36597],
13 "max_results": 15,
14 "exact_match": false,
15 "fuzzy": false,
16 "estimate_hno": true,
17 "debug": true,
18 "locale": "en"
19 }
20 """
21 val result = Http("https://search.magiclaneapis.com/v1")
22 .header("Content-Type", "application/json")
23 .header("Authorization", "YOUR_API_KEY_TOKEN")
24 .header("Accept-Encoding", "text")
25 .postData(request)
26 .option(HttpOptions.method("POST"))
27 .option(HttpOptions.readTimeout(10000)).asString
28 println(result)
29 println(result.code)
30 }
31}
scala
search request!
JSONPostReq.java
and then
compiled; at the commandline on either a Linux terminal or Windows command prompt type:
javac
JSONPostReq.java
java
JSONPostReq
complete minimal
java search request -
search
type
,
text
to search for (query),
target
list what to search for, in the case of POIs - also specify POI categories with
poi_categs
,
ref_location
a reference location in longitude and latitude around which to search;
debug
true causes resulting json to be pretty printed;
1import java.net.HttpURLConnection;
2import java.net.URL;
3import java.nio.charset.StandardCharsets;
4import java.io.BufferedReader;
5import java.io.InputStreamReader;
6import java.io.OutputStream;
7import java.io.IOException;
8public class JSONPostReq
9{
10 public static void main(String[] args) throws IOException
11 {
12 URL url = new URL("https://search.magiclaneapis.com/v1");
13 HttpURLConnection connection = (HttpURLConnection) url.openConnection();
14 connection.setRequestMethod("POST");
15 connection.setDoOutput(true);
16 connection.setRequestProperty("Content-Type","application/json");
17 connection.setRequestProperty("Authorization","YOUR_API_KEY_TOKEN");
18 String payload = "{"
19 +"\"text\": \"rest\","
20 +"\"target\": [\"pois\",\"addresses\"],"
21 +"\"poi_categs\": [\"food&drink\"],"
22 +"\"ref_location\": [4.89352, 52.36597],"
23 +"\"debug\": true"
24 +"}";
25 byte[] out = payload.getBytes(StandardCharsets.UTF_8);
26 OutputStream stream = connection.getOutputStream();
27 stream.write(out);
28 int responseCode = connection.getResponseCode();
29 System.out.println("response code: "+responseCode);
30 if (responseCode == HttpURLConnection.HTTP_OK)
31 {
32 BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
33 String inputLine;
34 while ((inputLine = in.readLine()) != null)
35 {
36 System.out.println(inputLine.toString());
37 }
38 in.close();
39 }
40 connection.disconnect();
41 }
42}
search request with all default values shown explicitly - this request is equivalent to, and produces the same output as, the previous request above;
1import java.net.HttpURLConnection;
2import java.net.URL;
3import java.nio.charset.StandardCharsets;
4import java.io.BufferedReader;
5import java.io.InputStreamReader;
6import java.io.OutputStream;
7import java.io.IOException;
8public class JSONPostReq
9{
10 public static void main(String[] args) throws IOException
11 {
12 try
13 {
14 URL url = new URL("https://search.magiclaneapis.com/v1");
15 HttpURLConnection connection = (HttpURLConnection) url.openConnection();
16 connection.setRequestMethod("POST");
17 connection.setDoOutput(true);
18 connection.setRequestProperty("Content-Type","application/json");
19 connection.setRequestProperty("Authorization","YOUR_API_KEY_TOKEN");
20 String payload = "{"
21 +"\"type\": \"free_text\","
22 +"\"text\": \"rest\","
23 +"\"target\": [\"pois\",\"addresses\"],"
24 +"\"poi_categs\": [\"food&drink\"],"
25 +"\"ref_location\": [4.89352, 52.36597],"
26 +"\"max_results\": 15,"
27 +"\"exact_match\": false,"
28 +"\"fuzzy\": false,"
29 +"\"estimate_hno\": true,"
30 +"\"debug\": true,"
31 +"\"locale\": \"en\""
32 +"}";
33 byte[] out = payload.getBytes(StandardCharsets.UTF_8);
34 OutputStream stream = connection.getOutputStream();
35 stream.write(out);
36 int responseCode = connection.getResponseCode();
37 System.out.println("response code: "+responseCode);
38 System.out.println(connection.getResponseMessage());
39 if (responseCode == HttpURLConnection.HTTP_OK)
40 {
41 BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
42 StringBuffer response = new StringBuffer();
43 String inputLine;
44 while ((inputLine = in.readLine()) != null)
45 {
46 response.append(inputLine);
47 System.out.println(inputLine.toString());
48 }
49 in.close();
50 //System.out.println(response.toString());
51 }
52 else
53 {
54 System.out.println("POST request FAILED");
55 }
56 connection.disconnect();
57 }
58 catch (Exception e)
59 {
60 System.out.println(e);
61 System.out.println("FAILED");
62 }
63 }
64}
search.js
and run at the commandline using nodejs.
In Linux, for example, if nodejs is not installed, it can be installed at the terminal commandline like this:
sudo
apt
install
nodejs
npm
install
xhr2
search.js
can be run at the commandline like this:
nodejs
search.js
complete minimal
javascript search request -
search
type
,
text
to search for (query),
target
list what to search for, in the case of POIs - also specify POI categories with
poi_categs
,
ref_location
a reference location in longitude and latitude around which to search;
debug
true causes resulting json to be pretty printed;
1var XMLHttpRequest = require("xhr2");
2const xhr = new XMLHttpRequest();
3xhr.open("POST", "https://search.magiclaneapis.com/v1");
4xhr.setRequestHeader("Content-Type","application/json");
5xhr.setRequestHeader("Authorization","YOUR_API_KEY_TOKEN");
6const body = JSON.stringify({
7 "text": "rest",
8 "target": ["pois", "addresses"],
9 "poi_categs": ["food&drink"],
10 "ref_location": [4.89352, 52.36597],
11 "debug": true
12});
13xhr.onload = () => {
14 console.log((xhr.responseText));
15};
16xhr.send(body);
search request with all default values shown explicitly - this request is equivalent to, and produces the same output as, the previous request above;
1var XMLHttpRequest = require("xhr2");
2const xhr = new XMLHttpRequest();
3xhr.open("POST", "https://search.magiclaneapis.com/v1");
4xhr.setRequestHeader("Content-Type","application/json");
5xhr.setRequestHeader("Authorization","YOUR_API_KEY_TOKEN");
6const body = JSON.stringify({
7 "type": "free_text",
8 "text": "rest",
9 "target": ["pois", "addresses"],
10 "poi_categs": ["food&drink"],
11 "ref_location": [4.89352, 52.36597],
12 "max_results": 15,
13 "exact_match": false,
14 "fuzzy": false,
15 "estimate_hno": true,
16 "debug": true,
17 "locale": "en"
18});
19xhr.onload = () => {
20 if (xhr.readyState == 4 && xhr.status == 200) {
21 console.log((xhr.responseText));
22 } else {
23 console.log(`error: ${xhr.status}`);
24 }
25};
26xhr.send(body);
search.go
and run at the commandline using go.
In Linux, for example, if go is not installed, it can be installed at the terminal commandline like this:
sudo
apt
install
golang
search.go
can be run at the commandline like this:
go
run
search.go
complete minimal go search request:
1package main
2import (
3 "fmt"
4 "bytes"
5 "net/http"
6 "io/ioutil"
7)
8
9func main() {
10 reqUrl := "https://search.magiclaneapis.com/v1"
11 var data = []byte(`{
12 "text": "rest",
13 "target": ["pois", "addresses"],
14 "poi_categs": ["food&drink"],
15 "ref_location": [4.89352, 52.36597],
16 "debug": true
17 }`)
18 req, _ := http.NewRequest("POST", reqUrl, bytes.NewBuffer(data))
19 req.Header.Add("Content-Type", "application/json")
20 req.Header.Add("Authorization", "YOUR_API_KEY_TOKEN")
21 res, _ := http.DefaultClient.Do(req)
22 defer res.Body.Close()
23 body, _ := ioutil.ReadAll(res.Body)
24 fmt.Println(res)
25 fmt.Println(string(body))
26}
search request with all default values shown explicitly - this request is equivalent to, and produces the same output as, the previous request above;
1package main
2import (
3 "fmt"
4 "bytes"
5 "net/http"
6 "io/ioutil"
7)
8
9func main() {
10 reqUrl := "https://search.magiclaneapis.com/v1"
11 var data = []byte(`{
12 "type": "free_text",
13 "text": "rest",
14 "target": ["pois", "addresses"],
15 "poi_categs": ["food&drink"],
16 "ref_location": [4.89352, 52.36597],
17 "max_results": 15,
18 "exact_match": false,
19 "fuzzy": false,
20 "estimate_hno": true,
21 "debug": true,
22 "locale": "en"
23 }`)
24 req, _ := http.NewRequest("POST", reqUrl, bytes.NewBuffer(data))
25 req.Header.Add("Content-Type", "application/json")
26 req.Header.Add("Authorization", "YOUR_API_KEY_TOKEN")
27 res, _ := http.DefaultClient.Do(req)
28 defer res.Body.Close()
29 body, _ := ioutil.ReadAll(res.Body)
30 fmt.Println(res)
31 fmt.Println(string(body))
32}
To install dart on Linux (debian/ubuntu flavors), for example, it is best to download the
.deb
package from the Linux tab in the above link, such as
dart_3.0.5-1_amd64.deb
and install it like this:
sudo
dpkg
-i
dart_3.0.5-1_amd64.deb
At a terminal/command prompt, type:
dart
create
myapp
to create a new dart application named
myapp
. A directory named
myapp
is created
in the current directory, containing all necessary files. Go into this new directory:
cd
myapp
User your favorite text editor, such as
vim
,
geany
or
notepad
to edit the
pubspec.yaml
file and add this dependency to the dependencies section as shown, then save it:
dependencies:
http:
^1.0.0
Next, edit the dart source code in
lib/myapp.dart
to look like this,
without the line numbers - those are for reference only:
complete search request in
dart
with
all default values shown explicitly
-
1import 'dart:io';
2import 'dart:async';
3import 'dart:convert';
4import 'package:http/http.dart' as http;
5
6calculate() async
7{
8 try
9 {
10 var sendString =
11 {
12 "type": "free_text",
13 "text": "rest",
14 "target": ["pois", "addresses"],
15 "poi_categs": ["food&drink"],
16 "ref_location": [4.89352, 52.36597],
17 "max_results": 15,
18 "exact_match": false,
19 "fuzzy": false,
20 "estimate_hno": true,
21 "debug": true,
22 "locale": "en"
23 };
24 final response = await http.post(
25 Uri.parse("https://search.magiclaneapis.com/v1"),
26 headers: {
27 "Content-Type": "application/json",
28 "Authorization": "YOUR_API_KEY_TOKEN"
29 //"Access-Control-Allow-Origin": "*"
30 },
31 body: jsonEncode(sendString)
32 );
33 print("${response.statusCode}");//2 equivalent ways to print output
34 //print("${response.body}");
35 //print(response.statusCode);
36 print(response.body);
37 }
38 catch(e)
39 {
40 print(e);
41 }
42}
You should replace the string “YOUR_API_KEY_TOKEN” with your actual API key token string.
Now save the
lib/myapp.dart
file shown above, go to the
myapp
directory, and run it like this:
dart
run
sudo
apt
install
perl
sudo
cpan
JSON
search.pl
(without the line numbers - those are for reference)
and run it:
perl
search.pl
1#! /usr/bin/env perl
2use strict;
3use warnings;
4use LWP::UserAgent;
5use HTTP::Request;
6use JSON;
7
8my $url = 'https://search.magiclaneapis.com/v1';
9my $json = '{
10 "text": "rest",
11 "target": ["pois", "addresses"],
12 "poi_categs": ["food&drink"],
13 "ref_location": [4.89352, 52.36597],
14 "debug": true
15 }';
16my $req = HTTP::Request->new( 'POST', $url );
17$req->header( 'Content-Type' => 'application/json',
18'Authorization' => 'YOUR_API_KEY_TOKEN');
19$req->content( $json );
20my $ua = LWP::UserAgent->new;
21my $res = $ua->request( $req );
22print $res->decoded_content;
search.pl
(without the line numbers - those are for reference)
and run it:
perl
search.pl
1#! /usr/bin/env perl
2use strict;
3use warnings;
4use LWP::UserAgent;
5use HTTP::Request;
6use JSON;
7
8my $url = 'https://search.magiclaneapis.com/v1';
9my $json = '{
10 "type": "free_text",
11 "text": "rest",
12 "target": ["pois", "addresses"],
13 "poi_categs": ["food&drink"],
14 "ref_location": [4.89352, 52.36597],
15 "max_results": 15,
16 "exact_match": false,
17 "fuzzy": false,
18 "estimate_hno": true,
19 "debug": true,
20 "locale": "en"
21 }';
22my $req = HTTP::Request->new( 'POST', $url );
23$req->header( 'Content-Type' => 'application/json',
24'Authorization' => 'YOUR_API_KEY_TOKEN');
25$req->content( $json );
26my $ua = LWP::UserAgent->new;
27my $res = $ua->request( $req );
28print $res->decoded_content;
search.php
and run at the commandline using php.
php
is not installed, it can be installed at the terminal commandline like this:
sudo
apt
install
php
php-curl
search.php
can be run at the commandline like this:
php
search.php
complete minimal php search request:
1<?php
2$mycurl = curl_init("https://search.magiclaneapis.com/v1");
3if ($mycurl === false) {
4 print "curl initialization FAILED\n";
5}
6$payload = array(
7 "text" => "rest",
8 "target" => array("pois", "addresses"),
9 "poi_categs" => array("food&drink"),
10 "ref_location" => array(4.89352, 52.36597),
11 "debug" => true
12 );
13$data_string = json_encode($payload);
14curl_setopt($mycurl, CURLOPT_CUSTOMREQUEST, "POST");
15curl_setopt($mycurl, CURLOPT_POSTFIELDS, $data_string);
16curl_setopt($mycurl, CURLOPT_RETURNTRANSFER, true);
17curl_setopt($mycurl, CURLOPT_FOLLOWLOCATION, true);
18curl_setopt($mycurl, CURLOPT_HTTPHEADER, array(
19 "Content-Type: application/json",
20 "Authorization: YOUR_API_KEY_TOKEN"
21 ));
22$result = curl_exec($mycurl);
23
24if ($result === false) {
25 print "POST request FAILED " . curl_error($mycurl) . " errno: " . curl_errno($mycurl) . "\n";
26}
27else { var_dump($result); }
28
29$httpReturnCode = curl_getinfo($mycurl, CURLINFO_HTTP_CODE);
30if ($httpReturnCode != "200") {
31 print "HTTP return code should be 200, got: " . $httpReturnCode . "\n";
32}
33if (is_resource($mycurl)) {
34 curl_close($mycurl);
35}
36?>
search request with all default values shown explicitly - this request is equivalent to, and produces the same output as, the previous request above;
1<?php
2$mycurl = curl_init("https://search.magiclaneapis.com/v1");
3if ($mycurl === false) {
4 print "curl initialization FAILED\n";
5}
6$payload = array(
7 "type" => "free_text",
8 "text" => "rest",
9 "target" => array("pois", "addresses"),
10 "poi_categs" => array("food&drink"),
11 "ref_location" => array(4.89352, 52.36597),
12 "max_results" => 15,
13 "exact_match" => false,
14 "fuzzy" => false,
15 "estimate_hno" => true,
16 "debug" => true,
17 "locale" => "en"
18 );
19$data_string = json_encode($payload);
20//curl_setopt($mycurl, CURLOPT_URL, "https://search.magiclaneapis.com/v1");
21curl_setopt($mycurl, CURLOPT_CUSTOMREQUEST, "POST");
22curl_setopt($mycurl, CURLOPT_POSTFIELDS, $data_string);
23curl_setopt($mycurl, CURLOPT_RETURNTRANSFER, true);
24curl_setopt($mycurl, CURLOPT_FOLLOWLOCATION, true);
25curl_setopt($mycurl, CURLOPT_HTTPHEADER, array(
26 "Content-Type: application/json",
27 "Authorization: YOUR_API_KEY_TOKEN"
28 ));
29$result = curl_exec($mycurl);
30
31if ($result === false) {
32 print "POST request FAILED " . curl_error($mycurl) . " errno: " . curl_errno($mycurl) . "\n";
33}
34else { var_dump($result); }
35
36$httpReturnCode = curl_getinfo($mycurl, CURLINFO_HTTP_CODE);
37if ($httpReturnCode != "200") {
38 print "HTTP return code should be 200, got: " . $httpReturnCode . "\n";
39}
40if (is_resource($mycurl)) {
41 curl_close($mycurl);
42}
43?>
sudo
apt
install
r-base-dev
R
httr
package within R like this:
install.packages("httr")
complete minimal
R search request:
note that the
debug
parameter is omitted, as the json is stored in the response variable, not printed
directly, so formatting the json output is done locally by the
toJSON()
function:
pretty
=
TRUE
;
(copy and paste the code into the R interpreter, without the line numbers - those are for reference)
1require(httr)
2require(jsonlite)
3body = '{
4 "text": "rest",
5 "target": ["pois", "addresses"],
6 "poi_categs": ["food&drink"],
7 "ref_location": [4.89352, 52.36597]
8 }'
9result <- POST("https://search.magiclaneapis.com/v1", body = body,
10add_headers(.headers = c("Content-Type"="application/json", "Authorization"="YOUR_API_KEY_TOKEN")))
11toJSON(content(result), pretty = TRUE)
search request with all default values shown explicitly - this request is equivalent to, and produces the same output as, the previous request above;
1require(httr)
2require(jsonlite)
3body = '{
4 "type": "free_text",
5 "text": "rest",
6 "target": ["pois", "addresses"],
7 "poi_categs": ["food&drink"],
8 "ref_location": [4.89352, 52.36597],
9 "max_results": 15,
10 "exact_match": false,
11 "fuzzy": false,
12 "estimate_hno": true,
13 "debug": true,
14 "locale": "en"
15 }'
16result <- POST("https://search.magiclaneapis.com/v1", body = body,
17add_headers(.headers = c("Content-Type"="application/json", "Authorization"="YOUR_API_KEY_TOKEN")))
18toJSON(content(result), pretty = TRUE)
To exit the R environment, type
q()
search.rb
and run at the commandline using ruby.
In Linux, for example, if ruby is not installed, it can be installed at the terminal commandline like this:
sudo
apt
install
ruby
search.rb
can be run at the commandline like this:
ruby
search.rb
complete minimal ruby search request:
1require "json"
2require "uri"
3require "net/http"
4require "openssl"
5
6url = URI("https://search.magiclaneapis.com/v1")
7http = Net::HTTP.new(url.host, url.port)
8http.use_ssl = true
9request = Net::HTTP::Post.new(url)
10request["Content-Type"] = "application/json"
11request["Accept-Encoding"] = "text"
12request["Authorization"] = "YOUR_API_KEY_TOKEN"
13request.body =
14{
15 "text": "rest",
16 "target": ["pois", "addresses"],
17 "poi_categs": ["food&drink"],
18 "ref_location": [4.89352, 52.36597],
19 "debug": true
20}.to_json
21puts "sent"
22response = http.request(request)
23puts response.read_body
search request with all default values shown explicitly - this request is equivalent to, and produces the same output as, the previous request above;
1require "json"
2require "uri"
3require "net/http"
4require "openssl"
5
6url = URI("https://search.magiclaneapis.com/v1")
7http = Net::HTTP.new(url.host, url.port)
8http.use_ssl = true
9request = Net::HTTP::Post.new(url)
10request["Content-Type"] = "application/json"
11request["Accept-Encoding"] = "text"
12request["Authorization"] = "YOUR_API_KEY_TOKEN"
13request.body =
14{
15 "type": "free_text",
16 "text": "rest",
17 "target": ["pois", "addresses"],
18 "poi_categs": ["food&drink"],
19 "ref_location": [4.89352, 52.36597],
20 "max_results": 15,
21 "exact_match": false,
22 "fuzzy": false,
23 "estimate_hno": true,
24 "debug": true,
25 "locale": "en"
26}.to_json
27puts "sent"
28response = http.request(request)
29puts response.read_body
Save the following in a text file named
Cargo.toml
(case-sensitive).
This contains the configuration and dependencies required for compilation.
1[package]
2name = "restpost"
3version = "0.1.0"
4edition = "2018"
5
6[[bin]]
7name = "search"
8path = "search.rs"
9
10[dependencies]
11json = { version = "0.12.4" }
12reqwest = { version = "0.11.18", features = ["json", "blocking"] }
13serde_json = { version = "1.0.44" }
14tokio = { version = "1.28.2", features = ["macros", "full"] }
search request with all default values shown explicitly ;
Save the following rust program in a text file named
search.rs
1extern crate reqwest;
2#[tokio::main]
3async fn main() -> Result<(), reqwest::Error>
4{
5 let response = reqwest::Client::new()
6 .post("https://search.magiclaneapis.com/v1")
7 .header("Authorization", "YOUR_API_KEY_TOKEN")
8 .header("Content-Type", "application/json")
9 .header("Accept-Encoding", "text")
10 .json(&serde_json::json!({
11 "type": "free_text",
12 "text": "rest",
13 "target": ["pois", "addresses"],
14 "poi_categs": ["food&drink"],
15 "ref_location": [4.89352, 52.36597],
16 "max_results": 15,
17 "exact_match": false,
18 "fuzzy": false,
19 "estimate_hno": true,
20 "debug": true,
21 "locale": "en"
22 }))
23 .send().await?;
24 println!("{:?}",response.text().await?);
25 Ok(())
26}
sudo
apt
install
cargo
rustc
Cargo.toml
and
search.rs
:
cargo
b
cd
target/debug
./search
complete search request in
Matlab
with
all default values shown explicitly
-
1method = matlab.net.http.RequestMethod.POST
2f0 = matlab.net.http.HeaderField('Content-Type','application/json')
3f1 = matlab.net.http.HeaderField('Authorization','')
4header = [f0 f1]
5str = [ ...
6'{', ...
7 + '"type": "free_text",', ...
8 + '"text": "rest",', ...
9 + '"target": ["pois","addresses"],', ...
10 + '"poi_categs": ["food&drink"],', ...
11 + '"ref_location": [4.89352, 52.36597],', ...
12 + '"max_results": 15,', ...
13 + '"exact_match": false,', ...
14 + '"fuzzy": false,', ...
15 + '"estimate_hno": true,', ...
16 + '"debug": true,', ...
17 + '"locale": "en"', ...
18 + '}' ]
19request = matlab.net.http.RequestMessage( method, header, jsondecode(str) );
20response = request.send( 'https://search.magiclaneapis.com/v1' );
21jsonencode(response.Body.Data,"PrettyPrint",true)
search.m
and run at the
Matlab
command
prompt by typing
search
and pressing enter. The current working directory shown at the top of the
window should be set to the directory where
search.m
was saved.
complete minimal
scilab search request:
note that the
debug
parameter is omitted, as the json is stored in the result variable, not printed
directly, so formatting the json output is done locally by the
toJSON()
function, where 3 is the number of
spaces to use for indentation (if this number is 0, then the json output is not indented/pretty printed)
1jsondata = ...
2"{" ...
3+"text: rest," ...
4+"target: [pois,addresses]," ...
5+"poi_categs: [food&drink]," ...
6+"ref_location: [4.89352, 52.36597]" ...
7+"}"
8[result, status] = http_post("https://search.magiclaneapis.com/v1", toJSON(fromJSON(jsondata)), format="json", auth="YOUR_API_KEY_TOKEN" );
9toJSON(result,3)
search request with all default values shown explicitly - this request is equivalent to, and produces the same output as, the previous request above;
1jsondata = ...
2"{" ...
3+"type: free_text," ...
4+"text: rest," ...
5+"target: [pois,addresses]," ...
6+"poi_categs: [food&drink]," ...
7+"ref_location: [4.89352, 52.36597]," ...
8+"max_results: 15," ...
9+"exact_match: false," ...
10+"fuzzy: false," ...
11+"estimate_hno: true," ...
12+"debug: true," ...
13+"locale: en" ...
14+"}"
15
16[result, status] = http_post("https://search.magiclaneapis.com/v1", toJSON(fromJSON(jsondata)), format="json", auth="YOUR_API_KEY_TOKEN" );
17
18toJSON(result,3)
In a linux terminal you can also send the request directly from the command line, without a file, like this: (this method does not work on windows)
1curl "https://search.magiclaneapis.com/v1" -X POST -H "Content-Type: application/json" -H "Authorization: YOUR_API_KEY_TOKEN" -d \
2'{
3...
4}'
The only difference is the added backslash after -d, and then the filename
@/home/user/payload.json
is replaced with the contents of
the json file, starting with the next line - note that a single quote ‘ is added before the leading
curly brace { and after the trailing curly brace } to enclose the file contents in single quotes - no backslashes are needed
between the single quotes.
Request parameter definitions ¶
Request body schema:
|
|
---|---|
key |
value |
|
Search type - for “free_text” search, a search string must be provided as value for the “text” key; or, “around_location” - search type, search around given location specified by longitude, latitude coordinates to the “ref_location” key
Type:
Default value:
Possible values - 1 of: “free_text”, “around_location” |
(conditional mandatory parameter) |
String to search for - must be specified if search “type” is “free_text”
Type:
Default value: empty |
|
Target type to search for - if none specified, then the search result will contain only settlements/cities
Type:
Default value: none Possible values - 0 or more of: “pois”, “addresses” |
|
If “pois” was included as value for the “target” key, the POI (point of interest) categories to search for can be specified using “poi_categs”; if no categories are specified, all are selected for the search
Type:
Default value: all categories selected for search Possible values - 0 or more of: “gas_stations”, “parking”, “food&drink”, “accommodation”, “medical_services”, “shopping”, “car_services”, “public_transport”, “wiki”, “education”, “entertainment”, “public_services”, “geographic_area”, “business”, “sightseeing”, “religious_places”, “roadside”, “sports”, “uncategorized”, “hydrants”, “emergency_services_support”, “civil_emergency_infrastructure” |
|
If “pois” was included as value for the “target” key, the POI (point of interest) categories to search for can be specified using “poi_categs”; however, when searching for a specific type of POI, “poi_subcategs” offers a higher resolution to the search.
Type:
Default value: all subcategories of the specified “poi_categs” parent category are selected for search As an example, if the category “food&drink” is specified for “poi_categs”, this includes all “poi_subcategs” for “food&drink”; however, if searching specifically for a tea house or coffee shop, then, instead of specifying the entire [“food&drink”] parent category for “poi_categs”, specify the subcategories [“tea_house”,”coffee_shop”] for “poi_subcategs”. These are the POI subcategories for each of the POI categories shown in “poi_categs” above: |
Select a POI category to see its POI subcategories:
petrol_station
charging_station
bicycle_charging_station
park_and_ride
parking_garage
parking_lot
bicycle_parking
rv_park
truck_parking
truck_stop
parking_meter
bar
coffee_shop
restaurant
specialty_food_store
tea_house
wine_and_spirits
winery
drinking_water
fast_food
bakery
camping
hotel
accommodation
utilities
alpine_hut
chalet
booking.com_hotel
dentist
health_care_service
hospital
medical_service
optician
pharmacy
physician
retirement_home
veterinarian
emergency_service
automobile_dealership
bookstore
bicycle_shop
clothing_store
electronics_store
convenience_store
department_store
discount_store
entertainment_electronics
floor_coverings_and_carpets
flowers
furniture
garden_centre
gift_shop
glass_and_windows
grocery
hairdresser
hardware_store
home_improvement_centre
home_improvement
home_specialty_store
lottery_shop
major_appliance
men's
apparel
motorcycle_dealership
office_supply_store
other_general_merchandise
paint_shop
photography
music
shoe_store
shopping
specialty_clothing_store
specialty_store
sporting_goods_store
variety_store
women's
apparel
agriculture
butcher
jewellery
do_it_yourself
vending_machine
bicycle_tube_vending_machine
cigarettes_vending_machine
coffee_vending_machine
drinks_vending_machine
food_vending_machine
newspaper_vending_machine
auto_dealership_-_used_cars
auto_parts
auto_service
automobile_club
car_wash
rental_car_agency
car_sharing
airport
bicycle_rental
bus_station
commuter_train_station
ferry_terminal
local_transit
marina
subway_entrance
public_transit_stop
ski_lift
taxi_stand
train_station
transportation_service
subway_station
helipad
tram_station
public_transit_tickets_kiosk
wikipedia
higher_education
library
school
science_and_research_institute
amusement_park
animal_park
banquet_hall
casino
cinema
cocktail_lounge
night_club
nightlife
performing_arts
video_rental
city_hall
civic_centre
convention_centre
county_council
court_house
embassy
fire_station
government_office
military_base
police_service
police_station
post_office
public_toilets
social_service
waste_and_sanitary
child_care_centre
recycling
animal_waste_bags_dispenser
parcel_locker
border_crossing
recreation_area
playground
peak
cave
archaeological_site
water
island
national_park
forest
atm
bank
boats
business_facility
business_services
cheque_cashing_service
dry_cleaning_and_laundry
computers_and_software
currency_exchange
funeral_director
industrial
timber
money_transferring_service
mover
communication
real_estate_agency
repair_service
storage
tailor_shop
tax_services
telecom
toll_station
travel_agent
weigh_station
attorney
bicycle_service
route_66
historical_monument
museum
tourist_attraction
tourist_information
windmill
viewpoint
lighthouse
cemetery
church
place_of_worship
synagogue
mosque
temple
highway_exit
race_track
rest_area
road_assistance
shelter
traffic_light
stop_sign
give_way_sign
traffic_calming
pedestrian_traffic_light
bicycle_traffic_light
pedestrian_crossing
bowling_centre
golf_course
golf_practice_range
health_club
ice_skating
swimming_pool
recreation
ski_resort
sporting_and_instructional_camp
sports_activities
sports_centre
sports_complex
tree
rope
loading_dock
fire_hydrant
pillar_hydrant
underground_hydrant
wall_hydrant
water_tank_hydrant
pond_hydrant
pipe_hydrant
defibrillator
first_aid_kit
ambulance_station
emergency_phone
emergency_landing_site
emergency_ward_entrance
emergency_ward_entrance_-_rescue_service
emergency_ward_entrance_-_walk_in
emergency_access_point
emergency_assembly_point
emergency_assembly_point_-_earthquake
emergency_assembly_point_-_fire
emergency_assembly_point_-_flood
emergency_assembly_point_-_landslide
emergency_assembly_point_-_tornado
emergency_assembly_point_-_tsunami
siren
fire_siren
civil_defense_siren
tornado_siren
tsunami_siren
air_raid_siren
Request body schema:
|
|
---|---|
key |
value |
(conditional mandatory parameter) |
Longitude, latitude reference location for the search - must be specified if search “type” is “around_location”
Type: array of 2 doubles in format
|
|
Specify maximum number of search results to return
Type:
Default value:
|
|
If true, only exact word matches for the search string filter are returned in the results
Type:
Default value:
|
|
If true, enables search string filter corrections using a fuzzy algorithm when no results are found
Type:
Default value:
|
|
If true, when only start and end house numbers are present on a street, an estimation of the searched house number is made, using an interpolation algorithm
Type:
Default value:
|
|
If true, the JSON output is formatted for easy reading
Type:
Default value:
|
|
The ISO 639-1 language for the search result
Type:
Default value:
|
Response ¶
MagicLane header
1{
2 "info": {
3 "copyrights": [
4 "MagicLane"
5 ]
6 },
7 "results": [
Search results
Each result item is given in a JSON block as shown below.
The coordinates in longitude, latitude (degrees). Location name, description and address components. Location contact details, such as phone number, email and URL, if available. Also wikipedia info and native location name, if available, and distance from reference location, in meters.
1{
2 "coordinates": [
3 4.8887434374999996223,
4 52.357778125000002944
5 ],
6 "name": "Le Restaurant",
7 "description": "Restaurant",
8 "address": {
9 "street name": "Frans Halsstraat",
10 "street number": "26-H",
11 "settlement": "Zuid",
12 "city": "Amsterdam",
13 "county": "North Holland",
14 "country": "Netherlands",
15 "country code": "NLD"
16 },
17 "contact": {
18 "URL": "https://www.le-restaurant.nl"
19 },
20 "native_name": "Le Restaurant",
21 "distance": 966
22},