SlideShare ist ein Scribd-Unternehmen logo
1 von 11
Stefano Dindo
Mail: s.dindo@zero12.it
Twitter: @stefanodindo
Corporate 1   Corporate 2
                                                                                      Corporate N


                                                                                ...
Hierarchical organization of users in the company




                                                       Admin         Admin
                                                                                         Admin




                                                    Clerk Users   Clerk Users
                                                                                      Clerk Users
API
http://www.drivefarm.com/developer/
OAuth 2.0


                             (1) Redirect su Login Page


                                 (2) Response code

   Client App


           (3) The codice is passed to the Server




                                              (4) getToken(code)


                                             (5) Response is sent
                                                 access_token

                                           (6) API method are colled
                                                by access_token


                                             (7) Response is sent in
                                                  JSON format
                      Server App
List the contents of the root folder

Java                                                    Python
String result = null;                                   import urllib
String urlStr = "https://www.drivefarm.com/api" +       import httplib
    "/folderContent?accessToken=ACCESS_TOKEN&path=/";   import json

try {                                                   data = {}
    URL url = new URL(urlStr);                          data['accessToken'] = ’ACCESS_TOKEN'
    URLConnection conn = url.openConnection();          data['path'] = '/'
    BufferedReader rd = new BufferedReader(new
        InputStreamReader(conn.getInputStream()));      headers = {"Accept": "application/json"}
    StringBuffer sb = new StringBuffer();               query = urllib.urlencode(data)
    String line;
    while ((line = rd.readLine()) != null) {            conn = httplib.HTTPSConnection("www.drivefarm.com")
        sb.append(line);                                conn.request("GET", "/api/folderContent?" + query, None, hea
    }                                                   response = conn.getresponse()
    rd.close();                                         data = response.read()
                                                        conn.close()
    result = sb.toString();
}                                                       for f in json.loads(data)['files']:
catch (Exception e){                                        print f['path']
    // ...
}
System.out.println(result);

/// parsing JSON
Folder creation
Java                                                           Python
String url="http://www.drivefarm.com/api/createFolder”;        import urllib
String body = "{ "accessToken" : ”ACCESS_TOKEN", " +       import httplib
    ""path" : "/Path/To/Folder" }";                        import json

URL serverAddress = new URL(url);                              data = {}
                                                               data['accessToken'] = ’ACCESS_TOKEN'
HttpURLConnection connection =                                 data['path'] = '/Path/To/Folder'
    (HttpURLConnection) serverAddress.openConnection();
connection.setDoInput(true);                                   headers = {"Content-type": "application/json",
connection.setDoOutput(true);                                  "    "Accept": "application/json"}
connection.setUseCaches(false);        
connection.setRequestProperty("Content-Type”,                  conn = httplib.HTTPSConnection("www.drivefarm.com")
    "application/json");                                       conn.request("POST", "/api/createFolder", json.dumps(data), headers)
connection.setRequestProperty("Accept", "application/json");   response = conn.getresponse()
connection.setRequestMethod("POST");                           status = response.status
connection.connect();                                          data = response.read()
                                                               conn.close()
DataOutputStream dos =
    new DataOutputStream(connection.getOutputStream() );       print json.loads(data)
dos.write(body.getBytes());
dos.close();

BufferedReader br = new BufferedReader(
     new InputStreamReader(connection.getInputStream()));
StringBuffer sb = new StringBuffer();
String str = br.readLine();
while(str != null){
     sb.append(str);
     str = br.readLine();
}
br.close();

System.out.println(sb.toString());
File upload
Java                                                                 Python
String url="http://www.drivefarm.com/api/fileUpload”;                import     urllib
                                                                     import     httplib
// ...                                                               import     json
String boundary = "AaB03x";                                          import     os
int totalBodyLength = ...                                            import     stat
// ...
                                                                     BODY   = '--AaB03xrn'
connection.setRequestProperty("Content-Type”,                        BODY   = BODY + 'Content-Disposition: form-data; name="fileUpload"r
    multipart/form-data; boundary=" + boundary);                     n'
connection.setRequestProperty("Content-Length", totalBodyLength);    BODY   =   BODY   +   'rn'
connection.setRequestProperty("Accept", "application/json");         BODY   =   BODY   +   '%srn'
connection.setRequestMethod("POST");                                 BODY   =   BODY   +   '--AaB03xrn'
connection.connect();                                                BODY   =   BODY   +   'Content-Disposition: form-data; name="uploadedFile"r
                                                                     n'
DataOutputStream dos =                                               BODY   =   BODY   +   'Content-Type: application/octet-streamrn'
    new DataOutputStream(connection.getOutputStream());              BODY   =   BODY   +   'rn'
dos.writeBytes("--" + boundary + lineEnd);                           BODY   =   BODY   +   '%srn'
dos.writeBytes("Content-Disposition: form-data; "+                   BODY   =   BODY   +   '--AaB03x--rn'
    " name="fileUpload"" + lineEnd);
dos.writeBytes(lineEnd);                                             data = {}
dos.write(body.getBytes());                                          data['accessToken'] = ‘ACCESS_TOKEN'
dos.writeBytes(lineEnd);                                             data['path'] = '/Path/To/Folder/file.txt'
dos.writeBytes( "--"+boundary + lineEnd);                            data['size'] = os.stat('icon.png')[stat.ST_SIZE]
dos.writeBytes("Content-Disposition: form-data; "+
    "name="uploadedFile"" + lineEnd);                              f = open(‘file.txt', 'rb')
dos.writeBytes("Content-Type: application/octet-stream"+ lineEnd);   body = BODY % (json.dumps(data), f.read())
dos.writeBytes(lineEnd);                                             f.close()
// scrittura contenuto file
dos.writeBytes(lineEnd);                                             headers = {"Content-type": "multipart/form-data; boundary=AaB03x",
dos.writeBytes( "--" + boundary + "--"+ lineEnd);                        "Content-Length": "%d" % len(body),
dos.flush();                                                             "Accept": "application/json"}
dos.close();
                                                                     conn = httplib.HTTPSConnection("www.drivefarm.com")
// lettura risposta JSON                                             conn.request("POST", "/api/fileUpload", body, headers)
                                                                     response = conn.getresponse()
                                                                     status = response.status
                                                                     data = response.read()
                                                                     conn.close()

                                                                     print json.loads(data)
Example of upload with browser

<html>

<head>
  <title>POST Test</title>
</head>

<body>

  <form action="https://www.drivefarm.com/api/fileUpload"
    enctype="multipart/form-data"
    method="post">

    <table>
      <tr>
        <!--
        Campo HTML in cui inserire i dati JSON formattati. Esempio:
        {"accessToken":”ACCESS_TOKEN","size":1234,"path":"/path/to/file.txt"}
        -->
        <td>fileUpload</td>
        <td><input type="text" name="fileUpload"/></td>
      </tr>
      <tr>
        <td>uploadedFile</td>
        <td><input type="file" name="uploadedFile"/></td>
      </tr>
      <tr>
        <td colspan="2"><input type="submit" value="invia"/></td>
      </tr>
    </table>
  </form>

</body>
</html>
Request authorization + Request
        access token after user confirmation

https://www.drivefarm.com/api/auth?
client_id=CLIENT_ID&redirect_uri=REDIRECT_URI&response_type=code&scope=READ+WRITE


import urllib
import httplib
import json

data = {}
data['client_id'] = 'CLIENT_ID'
data['client_secret'] = 'CLIENT_SECRECT'
data['grant_type'] = 'authorization_code'
data['redirect_uri'] = 'REDIRECT_URI'
data['code'] = 'code'

print urllib.urlencode(data)

headers = {"Content-type": "application/x-www-form-urlencoded",
"   "Accept": "application/json"}

conn = httplib.HTTPSConnection("codemotion.drivefarm.com")
conn.request("POST", "/api/access", urllib.urlencode(data), headers)
response = conn.getresponse()
status = response.status
data = response.read()
conn.close()

print data
Grazie
Stefano Dindo
Mail: s.dindo@zero12.it
Twitter: @stefanodindo

Weitere ähnliche Inhalte

Andere mochten auch

Digital Strategic Planner Manifesto
Digital Strategic Planner ManifestoDigital Strategic Planner Manifesto
Digital Strategic Planner Manifesto
Stefania Fussi
 
Cloud App: Vantaggi per il Business
Cloud App: Vantaggi per il BusinessCloud App: Vantaggi per il Business
Cloud App: Vantaggi per il Business
Stefano Dindo
 
Aperitivo Innovativo: Mobile Strategy & Development
Aperitivo Innovativo: Mobile Strategy & DevelopmentAperitivo Innovativo: Mobile Strategy & Development
Aperitivo Innovativo: Mobile Strategy & Development
Stefano Dindo
 
Ennova_Digital Signage_Market_project
Ennova_Digital Signage_Market_projectEnnova_Digital Signage_Market_project
Ennova_Digital Signage_Market_project
Stefano Grigoletti
 

Andere mochten auch (20)

Business Agility - come competere nell'Era Digitale
Business Agility - come competere nell'Era DigitaleBusiness Agility - come competere nell'Era Digitale
Business Agility - come competere nell'Era Digitale
 
Coworking al Box 85 - 120 Euro/mese
Coworking al Box 85 - 120 Euro/meseCoworking al Box 85 - 120 Euro/mese
Coworking al Box 85 - 120 Euro/mese
 
Marketing business to business and Mobile marketing
Marketing business to business and Mobile marketingMarketing business to business and Mobile marketing
Marketing business to business and Mobile marketing
 
Il Nuovo Giornalista è Una Information Startup
Il Nuovo Giornalista è Una Information StartupIl Nuovo Giornalista è Una Information Startup
Il Nuovo Giornalista è Una Information Startup
 
Digital Strategic Planner Manifesto
Digital Strategic Planner ManifestoDigital Strategic Planner Manifesto
Digital Strategic Planner Manifesto
 
Cloud App: Vantaggi per il Business
Cloud App: Vantaggi per il BusinessCloud App: Vantaggi per il Business
Cloud App: Vantaggi per il Business
 
Aperitivo Innovativo: Mobile Strategy & Development
Aperitivo Innovativo: Mobile Strategy & DevelopmentAperitivo Innovativo: Mobile Strategy & Development
Aperitivo Innovativo: Mobile Strategy & Development
 
Web marketing turistico internazionale: 5 strategie con consigli pratici
Web marketing turistico internazionale: 5 strategie con consigli praticiWeb marketing turistico internazionale: 5 strategie con consigli pratici
Web marketing turistico internazionale: 5 strategie con consigli pratici
 
Mobile application il caso barilla i pasta
Mobile application   il caso barilla i pastaMobile application   il caso barilla i pasta
Mobile application il caso barilla i pasta
 
Ennova_Digital Signage_Market_project
Ennova_Digital Signage_Market_projectEnnova_Digital Signage_Market_project
Ennova_Digital Signage_Market_project
 
Presentazione docenti sul web e l'introduzione digitale nel design didattico
Presentazione docenti sul web e l'introduzione digitale nel design didattico Presentazione docenti sul web e l'introduzione digitale nel design didattico
Presentazione docenti sul web e l'introduzione digitale nel design didattico
 
Deploy MongoDB su Infrastruttura Amazon Web Services
Deploy MongoDB su Infrastruttura Amazon Web ServicesDeploy MongoDB su Infrastruttura Amazon Web Services
Deploy MongoDB su Infrastruttura Amazon Web Services
 
Coworking a Caserta - Box85 da 120 Euro/mese
Coworking a Caserta - Box85 da 120 Euro/meseCoworking a Caserta - Box85 da 120 Euro/mese
Coworking a Caserta - Box85 da 120 Euro/mese
 
Introduzione all'Agile Coaching
Introduzione all'Agile CoachingIntroduzione all'Agile Coaching
Introduzione all'Agile Coaching
 
Storytelling & Gaming
Storytelling & GamingStorytelling & Gaming
Storytelling & Gaming
 
QUI+ creative content delivery | italian partners for beacon solutions
QUI+ creative content delivery | italian partners for beacon solutionsQUI+ creative content delivery | italian partners for beacon solutions
QUI+ creative content delivery | italian partners for beacon solutions
 
Come costruire un progetto e-commerce
Come costruire un progetto e-commerceCome costruire un progetto e-commerce
Come costruire un progetto e-commerce
 
Business attraverso i Big Data
Business attraverso i Big DataBusiness attraverso i Big Data
Business attraverso i Big Data
 
Overview di MongoDB
Overview di MongoDBOverview di MongoDB
Overview di MongoDB
 
Presentazione finale laurea
Presentazione finale laureaPresentazione finale laurea
Presentazione finale laurea
 

Mehr von Stefano Dindo

Logstash: Progetto open per l'analisi dei log in tempo reale di architetture ...
Logstash: Progetto open per l'analisi dei log in tempo reale di architetture ...Logstash: Progetto open per l'analisi dei log in tempo reale di architetture ...
Logstash: Progetto open per l'analisi dei log in tempo reale di architetture ...
Stefano Dindo
 

Mehr von Stefano Dindo (13)

Big Data: Come usare le Machine Learning per migliorare il business
Big Data: Come usare le Machine Learning per migliorare il businessBig Data: Come usare le Machine Learning per migliorare il business
Big Data: Come usare le Machine Learning per migliorare il business
 
Business Agility - Come competere nell'Era Digitale
Business Agility - Come competere nell'Era DigitaleBusiness Agility - Come competere nell'Era Digitale
Business Agility - Come competere nell'Era Digitale
 
MongoDB Solution for Internet of Things and Big Data
MongoDB Solution for Internet of Things and Big DataMongoDB Solution for Internet of Things and Big Data
MongoDB Solution for Internet of Things and Big Data
 
Come creare infrastrutture Cloud Sicure
Come creare infrastrutture Cloud SicureCome creare infrastrutture Cloud Sicure
Come creare infrastrutture Cloud Sicure
 
Proximity marketing
Proximity marketing Proximity marketing
Proximity marketing
 
Proximity Marketing - che cos'è, come funziona e come realizzarlo tecnologica...
Proximity Marketing - che cos'è, come funziona e come realizzarlo tecnologica...Proximity Marketing - che cos'è, come funziona e come realizzarlo tecnologica...
Proximity Marketing - che cos'è, come funziona e come realizzarlo tecnologica...
 
Cultura Digitale e Data Design
Cultura Digitale e Data DesignCultura Digitale e Data Design
Cultura Digitale e Data Design
 
Internet of Things e manutenzione a distanza: 
disponibilità di nuove tecnolo...
Internet of Things e manutenzione a distanza: 
disponibilità di nuove tecnolo...Internet of Things e manutenzione a distanza: 
disponibilità di nuove tecnolo...
Internet of Things e manutenzione a distanza: 
disponibilità di nuove tecnolo...
 
Keep Calm & dai uno sguardo al futuro con nuove strategie di relazione con gl...
Keep Calm & dai uno sguardo al futuro con nuove strategie di relazione con gl...Keep Calm & dai uno sguardo al futuro con nuove strategie di relazione con gl...
Keep Calm & dai uno sguardo al futuro con nuove strategie di relazione con gl...
 
Logstash: Progetto open per l'analisi dei log in tempo reale di architetture ...
Logstash: Progetto open per l'analisi dei log in tempo reale di architetture ...Logstash: Progetto open per l'analisi dei log in tempo reale di architetture ...
Logstash: Progetto open per l'analisi dei log in tempo reale di architetture ...
 
Mobile & Cloud: quali servizi sono disponibili e come sfruttarli al meglio
Mobile & Cloud: quali servizi sono disponibili e come sfruttarli al meglioMobile & Cloud: quali servizi sono disponibili e come sfruttarli al meglio
Mobile & Cloud: quali servizi sono disponibili e come sfruttarli al meglio
 
Better Software 2012 - Dall'Idea all'App
Better Software 2012  - Dall'Idea all'AppBetter Software 2012  - Dall'Idea all'App
Better Software 2012 - Dall'Idea all'App
 
Google Wave il nuovo modo di comunicare
Google Wave il nuovo modo di comunicareGoogle Wave il nuovo modo di comunicare
Google Wave il nuovo modo di comunicare
 

DriveFarm API

  • 2. Corporate 1 Corporate 2 Corporate N ... Hierarchical organization of users in the company Admin Admin Admin Clerk Users Clerk Users Clerk Users
  • 4.
  • 5. OAuth 2.0 (1) Redirect su Login Page (2) Response code Client App (3) The codice is passed to the Server (4) getToken(code) (5) Response is sent access_token (6) API method are colled by access_token (7) Response is sent in JSON format Server App
  • 6. List the contents of the root folder Java Python String result = null; import urllib String urlStr = "https://www.drivefarm.com/api" + import httplib "/folderContent?accessToken=ACCESS_TOKEN&path=/"; import json try { data = {} URL url = new URL(urlStr); data['accessToken'] = ’ACCESS_TOKEN'    URLConnection conn = url.openConnection(); data['path'] = '/'    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); headers = {"Accept": "application/json"}    StringBuffer sb = new StringBuffer(); query = urllib.urlencode(data)    String line;    while ((line = rd.readLine()) != null) { conn = httplib.HTTPSConnection("www.drivefarm.com")        sb.append(line); conn.request("GET", "/api/folderContent?" + query, None, hea    } response = conn.getresponse()    rd.close(); data = response.read() conn.close()    result = sb.toString(); } for f in json.loads(data)['files']: catch (Exception e){ print f['path'] // ... } System.out.println(result); /// parsing JSON
  • 7. Folder creation Java Python String url="http://www.drivefarm.com/api/createFolder”; import urllib String body = "{ "accessToken" : ”ACCESS_TOKEN", " + import httplib ""path" : "/Path/To/Folder" }"; import json URL serverAddress = new URL(url); data = {} data['accessToken'] = ’ACCESS_TOKEN' HttpURLConnection connection = data['path'] = '/Path/To/Folder' (HttpURLConnection) serverAddress.openConnection(); connection.setDoInput(true); headers = {"Content-type": "application/json", connection.setDoOutput(true); " "Accept": "application/json"} connection.setUseCaches(false);         connection.setRequestProperty("Content-Type”, conn = httplib.HTTPSConnection("www.drivefarm.com") "application/json"); conn.request("POST", "/api/createFolder", json.dumps(data), headers) connection.setRequestProperty("Accept", "application/json"); response = conn.getresponse() connection.setRequestMethod("POST"); status = response.status connection.connect(); data = response.read()         conn.close() DataOutputStream dos = new DataOutputStream(connection.getOutputStream() ); print json.loads(data) dos.write(body.getBytes()); dos.close(); BufferedReader br = new BufferedReader( new InputStreamReader(connection.getInputStream())); StringBuffer sb = new StringBuffer(); String str = br.readLine(); while(str != null){    sb.append(str);  str = br.readLine(); } br.close(); System.out.println(sb.toString());
  • 8. File upload Java Python String url="http://www.drivefarm.com/api/fileUpload”; import urllib import httplib // ... import json String boundary = "AaB03x"; import os int totalBodyLength = ... import stat // ... BODY = '--AaB03xrn' connection.setRequestProperty("Content-Type”, BODY = BODY + 'Content-Disposition: form-data; name="fileUpload"r multipart/form-data; boundary=" + boundary); n' connection.setRequestProperty("Content-Length", totalBodyLength); BODY = BODY + 'rn' connection.setRequestProperty("Accept", "application/json"); BODY = BODY + '%srn' connection.setRequestMethod("POST"); BODY = BODY + '--AaB03xrn' connection.connect(); BODY = BODY + 'Content-Disposition: form-data; name="uploadedFile"r         n' DataOutputStream dos = BODY = BODY + 'Content-Type: application/octet-streamrn' new DataOutputStream(connection.getOutputStream()); BODY = BODY + 'rn' dos.writeBytes("--" + boundary + lineEnd); BODY = BODY + '%srn' dos.writeBytes("Content-Disposition: form-data; "+ BODY = BODY + '--AaB03x--rn' " name="fileUpload"" + lineEnd); dos.writeBytes(lineEnd); data = {} dos.write(body.getBytes()); data['accessToken'] = ‘ACCESS_TOKEN' dos.writeBytes(lineEnd); data['path'] = '/Path/To/Folder/file.txt' dos.writeBytes( "--"+boundary + lineEnd); data['size'] = os.stat('icon.png')[stat.ST_SIZE] dos.writeBytes("Content-Disposition: form-data; "+ "name="uploadedFile"" + lineEnd); f = open(‘file.txt', 'rb') dos.writeBytes("Content-Type: application/octet-stream"+ lineEnd); body = BODY % (json.dumps(data), f.read()) dos.writeBytes(lineEnd); f.close() // scrittura contenuto file dos.writeBytes(lineEnd); headers = {"Content-type": "multipart/form-data; boundary=AaB03x", dos.writeBytes( "--" + boundary + "--"+ lineEnd); "Content-Length": "%d" % len(body), dos.flush(); "Accept": "application/json"} dos.close(); conn = httplib.HTTPSConnection("www.drivefarm.com") // lettura risposta JSON conn.request("POST", "/api/fileUpload", body, headers) response = conn.getresponse() status = response.status data = response.read() conn.close() print json.loads(data)
  • 9. Example of upload with browser <html> <head> <title>POST Test</title> </head> <body> <form action="https://www.drivefarm.com/api/fileUpload" enctype="multipart/form-data" method="post"> <table> <tr> <!-- Campo HTML in cui inserire i dati JSON formattati. Esempio: {"accessToken":”ACCESS_TOKEN","size":1234,"path":"/path/to/file.txt"} --> <td>fileUpload</td> <td><input type="text" name="fileUpload"/></td> </tr> <tr> <td>uploadedFile</td> <td><input type="file" name="uploadedFile"/></td> </tr> <tr> <td colspan="2"><input type="submit" value="invia"/></td> </tr> </table> </form> </body> </html>
  • 10. Request authorization + Request access token after user confirmation https://www.drivefarm.com/api/auth? client_id=CLIENT_ID&redirect_uri=REDIRECT_URI&response_type=code&scope=READ+WRITE import urllib import httplib import json data = {} data['client_id'] = 'CLIENT_ID' data['client_secret'] = 'CLIENT_SECRECT' data['grant_type'] = 'authorization_code' data['redirect_uri'] = 'REDIRECT_URI' data['code'] = 'code' print urllib.urlencode(data) headers = {"Content-type": "application/x-www-form-urlencoded", " "Accept": "application/json"} conn = httplib.HTTPSConnection("codemotion.drivefarm.com") conn.request("POST", "/api/access", urllib.urlencode(data), headers) response = conn.getresponse() status = response.status data = response.read() conn.close() print data

Hinweis der Redaktion

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n