Use a REST API: Difference between revisions
(sort the entries) |
m (→{{header|JavaScript}}: header Javascript -> JavaScript) |
||
Line 173: | Line 173: | ||
}</lang> |
}</lang> |
||
=={{header| |
=={{header|JavaScript}}== |
||
{{incomplete|Javascript|This needs a way to submit events to Meetup.}} |
{{incomplete|Javascript|This needs a way to submit events to Meetup.}} |
Revision as of 22:31, 28 December 2014
To:
- Get a list of events
- Submit events
Using the Meetup.com API.
An API key is assumed to be supplied through an api_key.txt
file.
Solutions should be implemented without any meetup.com helper libraries, to make it easier to translate to languages which don't have such helper libraries. However, examples that do use helper libraries may be provided as an addition.
This task was created through Google Code-in
Java
EventGetter.java
<lang java>package src;
import java.io.BufferedReader; import java.io.FileReader; import java.net.URI;
import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.utils.URIBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils;
public class EventGetter {
String city = "";
String topic = "";
public String getEvent(String path_code,String key) throws Exception{ String responseString = "";
URI request = new URIBuilder() //We build the request URI .setScheme("http") .setHost("api.meetup.com") .setPath(path_code) //List of parameters : .setParameter("topic", topic) .setParameter("city", city) //End of params .setParameter("key", key) .build();
HttpGet get = new HttpGet(request); //Assign the URI to the get request System.out.println("Get request : "+get.toString());
CloseableHttpClient client = HttpClients.createDefault(); CloseableHttpResponse response = client.execute(get); responseString = EntityUtils.toString(response.getEntity());
return responseString; }
public String getApiKey(String key_path){ String key = "";
try{ BufferedReader reader = new BufferedReader(new FileReader(key_path)); //Read the file where the API Key is key = reader.readLine().toString(); //Store key reader.close(); } catch(Exception e){System.out.println(e.toString());}
return key; //Return the key value. }
}</lang>
Main.java <lang java>/*
* In this class, You can see the diferent * ways of asking for events. * */
package src;
import java.util.Iterator;
import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONValue; import org.json.simple.parser.JSONParser;
public class Main { public static void main(String[] args) {
String key_path = "API_key/api_key.txt"; //Path to API Key (api_key.txt) String key = ""; String path_code = "/2/open_events"; //PathCode for get-events //More PathCodes : http://www.meetup.com/meetup_api/docs/ String events = "";
EventGetter eventGetter = new EventGetter(); key = eventGetter.getApiKey(key_path);
/* * 1-PARAMETER EXAMPLE : */ eventGetter.topic = "photo"; //Set the parameter "topic" to "photo"
try { events = eventGetter.getEvent(path_code, key); //Store the event response into a String } catch (Exception e) {e.printStackTrace();} DecodeJSON(events); //Print JSON-parsed events info
/* * 2-PARAMETER EXAMPLE : */ eventGetter.topic = "tech"; //Set parameters eventGetter.city = "Barcelona"; try{ events = eventGetter.getEvent(path_code, key); }catch(Exception e){e.printStackTrace();} //System.out.println(events); //Print the events list (JSON)
/*
* MULTIPLE-TOPICS EXAMPLE :
* Separate topics by commas
*/
eventGetter.topic = "tech,photo,art"; //multiple topic separated by commas
eventGetter.city = "Barcelona";
try{
events = eventGetter.getEvent(path_code, key);
}catch(Exception e){e.printStackTrace();}
}
public static void DecodeJSON(String events){
try{ JSONParser parser = new JSONParser(); JSONObject obj = (JSONObject) parser.parse(events); JSONArray results = (JSONArray) obj.get("results"); System.out.println("Results : ");
Iterator i = results.iterator(); while(i.hasNext()){ JSONObject event = (JSONObject) i.next(); System.out.println("Name : "+event.get("name"));
if(event.containsKey("venue")){ JSONObject venue = (JSONObject) event.get("venue"); System.out.println("Location (city) : "+venue.get("city")); System.out.println("Location (adress) : "+venue.get("adress_1")); }
System.out.println("Url : "+event.get("event_url"));
System.out.println("Time : "+event.get("time"));
i.next();
}
} catch(Exception e){e.printStackTrace();} }
}</lang>
JavaScript
Made on node js. Run using 'node filename.js'
<lang javascript>var fs = require('fs'); var request = require('request');
var meetup = function() {
var key = fs.readFileSync('api_key.txt', 'utf-8'); var url = "https://api.meetup.com";
var composeURL = function(root, object) { return root + '?' + JSON.stringify(object).replace(/":"/g, '=').replace(/","/g, '&').slice(2, -2) }
var getEvent = function(params, callback) { params.key = key;
request.get(composeURL(url + '/2/open_events', params), function(err, res, body) { if ( err ) { console.error(err); return false; }
callback(JSON.parse(body)['results']); }) }
var postEvent = function(details, callback) { details.key = key;
/*if ( !details.group_id || !details.group_urlname || !details.name ) { console.error('The group_id, group_urlname, and name fields are mandatory.') }*/
request.post({ headers: { 'content-type' : 'application/x-www-form-urlencoded' }, url: url + '/2/event', form: details }, function(err, res, body) { callback(body); }) }
var parseEvent = function(mEvent) { var name = mEvent['name'] || ; var desc = mEvent['desc'] || ; var url = mEvent['url'] || ;
if ( mEvent['venue'] ) { var city = mEvent['venue']['city'] || ; var lat = mEvent['venue']['lat'] || ; var lon = mEvent['venue']['lon'] || ; } if ( mEvent['group'] ) var group = mEvent['group']['name'] || ;
var parsed = ;
if ( name ) parsed += 'Name: ' + name + '\n'; if ( desc ) parsed += 'Description: ' + desc + '\n'; if ( url ) parsed += 'Url: ' + url + '\n'; if ( city ) parsed += 'City: ' + city + '\n'; if ( lat ) parsed += 'Latitude: ' + lat + '\n'; if ( lon ) parsed += 'Longitude: ' + lon + '\n'; if ( group ) parsed += 'Group: ' + group + '\n';
return parsed;
};
var parseEvents = function(results) { console.log('a'); for ( var i = 0; i < results.length; i++ ) { console.log( parseEvent(results[i]) ); } }
return { getEvent: getEvent, parseEvents: parseEvents, postEvent: postEvent }
}
meetup().getEvent({
topic: 'photo', city: 'nyc'
}, function(results) {
meetup().parseEvents(results);
});
// Posting requires a valid group which is a paid feature
meetup().postEvent({
// group_id: 1, // group_urlname, name: 'Tomato'
}, function(result) {
console.log(result);
})</lang>
Python
eventGetter.py <lang python>#http://docs.python-requests.org/en/latest/ import requests import json
city = None topic = None
def getEvent(url_path, key) :
responseString = "" params = {'city':city, 'key':key,'topic':topic} r = requests.get(url_path, params = params) print(r.url) responseString = r.text return responseString
def getApiKey(key_path):
key = "" f = open(key_path, 'r') key = f.read() return key
def submitEvent(url_path,params):
r = requests.post(url_path, data=json.dumps(params)) print(r.text+" : Event Submitted")</lang>
main.py <lang python>import eventGetter as eg import json
def main():
url_path = "https://api.meetup.com" #Url to meetup API key_path = "api_key.txt" #Path to api_key.txt path_code = "" #var to store the url_path + the specific api path key = eg.getApiKey(key_path) #1-parameter get events example : print("1-PARAMETER EXAMPLE") path_code = url_path+"/2/open_events" eg.topic = "photo" response = eg.getEvent(path_code, key) decodeJSON(response)
#2-parameter get events example : print("\n") print("2-PARAMETER EXAMPLE") path_code = url_path+"/2/open_events" eg.topic = "photo" eg.city = "nyc" response = eg.getEvent(path_code, key) decodeJSON(response)
#Get GEO Example : print("\n") print("Get GEO Example") path_code = url_path+"/2/open_events" eg.topic = "photo" eg.city = None exclude = None response = eg.getEvent(path_code, key) decodeGEO(response)
#Exclude topics Example print("\n") print("EXCLUDE-TOPICS EXAMPLE") path_code = url_path+"/2/open_events" eg.topic = "photo" eg.city = None exclude = "club" response = eg.getEvent(path_code, key) decodeJSONExcluding(response, exclude)
def decodeJSON(response):
j = json.loads(response.encode('ascii','ignore').decode()) #This is a Python Dict (JSON array) i = 0 results = j['results'] while i<len(results): event = results[i] print("Event "+str(i)) print("Event name : "+event['name']) print("Event URL : "+event['event_url']) try : print("City : "+str(event['venue']['city'])) except KeyError : print("This event has no location assigned") try : print("Group : "+str(event['group']['name'])) except KeyError : print("This event is not related to any group") i+=1
def decodeJSONExcluding(response, exclude):
j = json.loads(response.encode('ascii','ignore').decode()) #This is a Python Dict (JSON array) i = 0 results = j['results'] while i<len(results): event = results[i] if 'description' in event : if exclude not in str(event['description']) : print("Event "+str(i)) print("Event name : "+event['name']) print("Event URL : "+event['event_url']) try : print("City : "+str(event['venue']['city'])) except KeyError : print("This event has no location assigned") try : print("Group : "+str(event['group']['name'])) except KeyError : print("This event is not related to any group") else : print("Event number "+str(i)+" is excluded by its keywords") i+=1
def decodeGEO(response):
j = json.loads(response.encode('ascii','ignore').decode()) #This is a Python Dict (JSON array) i = 0 results = j['results'] while i<len(results): event = results[i] print("Event "+str(i)) print("Event name : "+event['name']) try : print("Lat : "+str(event['venue']['lat'])) print("Lon : "+str(event['venue']['lon'])) except KeyError : print("This event has no location assigned") i+=1
main()</lang>