Use a REST API

From Rosetta Code
Revision as of 07:13, 27 December 2014 by rosettacode>Namanyayg
Use a REST API is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

To:

  1. Get a list of events
  2. 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

This example is incomplete. This needs a way to submit events to Meetup. Please ensure that it meets all task requirements and remove this message.

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>

Python

This example is incomplete. This needs a way to submit events to Meetup. Please ensure that it meets all task requirements and remove this message.

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>