EvernoteDevelopersevernote.com
Deprecated

Getting Started with the Evernote API

Sharing (and Un-Sharing) Notes

How to start and stop sharing a single note, as well as how to retrieve a list all of the shared notes in an Evernote account.

  • Single Note Sharing

    Single notes can be shared in one of two ways: publicly (using a public note URL) or via email. The latter isn’t exactly sharing as much as it is emailing a copy of a note, so we’re going to focus on the former: sharing via a public shared URL. Note that there isn’t a way to share a single note with only one other person; anybody who knows the URL for a shared note will be able to view it.

    In order to share a single note, you’ll need the following information:

    • The GUID of the note you’d like to share.
    • The ID of the Shard that houses the note to be shared.
    • A valid authentication token or developer token.
    • Initialized instances of NoteStore.Client and UserStore.Client

    The Shard ID can be determined at runtime by querying the UserStore:

    main.py
    def getUserShardId(authToken, userStore):
    	"""
    	Get the User from userStore and return the user's shard ID
    	"""
    	try:
    		user = userStore.getUser(authToken)
    	except (Errors.EDAMUserException, Errors.EDAMSystemException), e:
    		print "Exception while getting user's shardID:"
    		print type(e), e
    		return None
    	
    	if hasattr(user, 'shardId'):
    		return user.shardId
    	return None
    gistfile1.m
    - (void)getUserShardId {
        //Get the User from userStore and return the user's shard ID
        [[EvernoteUserStore userStore] getUserWithSuccess:^(EDAMUser *user) {
            NSString* shardId = user.shardId;
            NSLog(@"Shard id : %@",shardId);
        } failure:^(NSError *error) {
            NSLog(@"Error : %@",error);
        }];
    }
    example.rb
    def get_user_shard_id(user_store)
    
      # Get the User from userStore and return the user's shard ID
    
      begin
        user = user_store.getUser
        return user.shardId
      rescue Evernote::EDAM::Error::EDAMUserException, Evernote::EDAM::Error::EDAMSystemException => e
        puts "Exception while getting user's shardID:"
        puts e.inspect
      end
    
    end
    example.php
    <?php
    function getUserShardId($userStore) {
     
      // Get the User from userStore and return the user's shard ID
     
      try {
        $user = $userStore->getUser();
        return $user->shardId;
      } catch (EDAMUserException $e) {
        print "Exception while getting user's shardID:";
        print var_dump($e);
      } catch (EDAMSystemException $e) {
        print "Exception while getting user's shardID:";
        print var_dump($e);
      }
      return null;
    
    }
    ?>
    example.java
    public String getUserShardId(UserStoreClient userStore) {
    
    // Get the User from userStore and return the user's shard ID
    
      try {
        user = userStore.getUser();
        return user.getShardId();
      } catch (EDAMUserException e) {
        System.out.println("Exception while getting user's shardID:");
        System.out.println(e);
      } catch (EDAMSystemException e) {
        System.out.println("Exception while getting user's shardID:");
        System.out.println(e);
      } catch (TException e) {
        System.out.println("Exception while getting user's shardID:");
        System.out.println(e);
      }
      return null;
    
    }
    example.js
    function getUserShardId(userStore, callback) {
     
      // Get the User from userStore and return the user's shard ID
     
      userStore.getUser(function(user) {
        if (user.errorCode) {
          console.log("Exception while getting user's shardID:");
          console.log(user);
        } else {
          callback(user.shardId);
        }
      });
     
    }

    Assuming all of that is in place, sharing a note is actually quite simple. By calling NoteStore.shareNote and passing a valid authentication token and the GUID of the note you’d like to share. In return, you’ll get a Share Key from the Evernote Cloud API that can be used in conjunction with the note GUID to view a read-only version of the note.

    Here’s a snippet of code that illustrates how the whole process works:

    main.py
    def shareSingleNote(authToken, noteStore, userStore, noteGuid, shardId=None):
    	"""
    	Share a single note and return the public URL for the note
    	"""
    	if not shardId:
    		shardId = getUserShardId(authToken, userStore)
    		if not shardId:
    			raise SystemExit
    
    	try:
    		shareKey = noteStore.shareNote(authToken, noteGuid)
    	except (EDAMNotFoundException, EDAMSystemException, EDAMUserException), e:
    		print "Error sharing note:"
    		print type(e), e
    		return None
    
    	return "%s/shard/%s/sh/%s/%s" % \
    		(EN_URL, shardId, noteGuid, shareKey)
    gistfile1.m
    - (void)shareSingleNoteWithNoteGUID:(NSString*)noteGUID
                            withShardId:(NSString*)shardId {
        // Share a single note and return the public URL for the note
        [[EvernoteNoteStore noteStore] shareNoteWithGuid:noteGUID success:^(NSString *noteKey) {
            NSString* shareURL = [NSString stringWithFormat:@"%@/shard/%@/sh/%@/%@",[[EvernoteSession sharedSession] host] ,shardId,noteGUID, noteKey];
            NSLog(@"Share URL : %@",shareURL);
        } failure:^(NSError *error) {
            NSLog(@"Error : %@",error);
        }];
    }
    example.rb
    def share_single_note(note_store, user_store, note_guid, shard_id=nil)
    
      # Share a single note and return the public URL for the note
    
      shard_id ||= get_user_shard_id(user_store)
      raise "Couldn't get shard_id" unless shard_id
    
      begin
        share_key = note_store.shareNote(note_guid)
        return "#{EN_URL}/shard/#{shard_id}/sh/#{note_guid}/#{share_key}"
      rescue Evernote::EDAM::Error::EDAMNotFoundException,
        Evernote::EDAM::Error::EDAMSystemException,
        Evernote::EDAM::Error::EDAMUserException => e
        puts "Error sharing note:"
        puts e.inspect
      end
    
    end
    example.php
    <?php
    function shareSingleNote($noteStore, $userStore, $noteGuid, $shardId = null) {
    
        // Share a single note and return the public URL for the note
    
        if (!isset($shardId)) {
            $shardId = getUserShardId($userStore);
            if (!isset($shardId)) {
                throw new Exception();
            }
        }
    
        try {
            $shareKey = $noteStore->shareNote($noteGuid);
            return EN_URL . "/shard/" . $shardId . "/sh/" . $noteGuid . "/" . $shareKey;
        } catch (EDAMNotFoundException $e) {
            print "Error sharing note:";
            print var_dump(e);
        } catch (EDAMSystemException $e) {
            print "Error sharing note:";
            print var_dump(e);
        } catch (EDAMUserExceptipon $e) {
            print "Error sharing note:";
            print var_dump(e);
        }
        
        return null;
    
    }
    ?>
    example.java
    public String shareSingleNote(NoteStoreClient noteStore, UserStoreClient userStore, String noteGuid, String shardId) {
    
      // Share a single note and return the public URL for the note
    
      if (shardId == null) {
        shardId = getUserShardId(userStore);
      }
    
      try {
        String shareKey = noteStore.shareNote(noteGuid);
        return EN_URL + "/shard/" + shardId + "/sh/" + noteGuid + "/" + shareKey;
      } catch (EDAMNotFoundException e) {
        System.out.println("Error sharing note:");
        System.out.println(e);
      } catch (EDAMSystemException e) {
        System.out.println("Error sharing note:");
        System.out.println(e);
      } catch (EDAMUserException e) {
        System.out.println("Error sharing note:");
        System.out.println(e);
      } catch (TException e) {
        System.out.println("Error sharing note:");
        System.out.println(e);
      }
      
      return null;
    
    }
    example.js
    function shareSingleNote(noteStore, userStore, noteGuid, shardId, callback) {
     
      // Share a single note and return the public URL for the note
     
      noteStore.shareNote(noteGuid, function(shareKey) {
        if (shareKey.errorCode) {
          console.log("Error sharing note:");
          console.log(shareKey);
        } else {
          callback(EN_URL + "/shard/" + shardId + "/sh/" + noteGuid + "/" + shareKey);
        }
      });
     
    }

    Assuming nothing broke, the above function will return a public note URL that looks something like this:

    https://www.evernote.com/shard/s1/sh/36dd7123-12c0-457a-a6d0-75555fcc7770/3afc29de3493d0d333b54cf1822be92c

    The last two pieces of data in the URL are the note GUID and the share key.

  • Stop Sharing a Note

    This is about as close to a one-liner as you can get.

    You’ll need an initialized NoteStore.Client instance, a good authentication token and the GUID of the note in question. With those things in place, it’s as simple as calling NoteStore.stopSharingNote:

    main.py
    def stopSharingSingleNote(authToken, noteStore, noteGuid):
    	try:
    		noteStore.stopSharingNote(authToken, noteGuid)
    	except (EDAMNotFoundException, EDAMSystemException, EDAMUserException), e:
    		print "Error stopping sharing note:"
    		print type(e), e
    		return None
    	return noteGuid	
    gistfile1.m
    - (void)stopSharingSingleNoteWithNoteGUID:(NSString*)noteGUID {
        // Share a single note and return the public URL for the note
        [[EvernoteNoteStore noteStore] stopSharingNoteWithGuid:noteGUID success:^{
            NSLog(@"Stopped sharing note");
        } failure:^(NSError *error) {
            NSLog(@"Error : %@",error);
        }];
    }
    example.rb
    def stop_sharing_single_note(note_store, note_guid)
      begin
        note_store.stopSharingNote(note_guid)
        return note_guid
      rescue Evernote::EDAM::Error::EDAMNotFoundException,
        Evernote::EDAM::Error::EDAMSystemException,
        Evernote::EDAM::Error::EDAMUserException => e
        puts "Error stopping sharing note:"
        puts e.inspect
      end
    end
    example.php
    <?php
    
    function stopSharingSingleNote($noteStore, $noteGuid) {
        try {
            $noteStore->stopSharingNote($noteGuid);
            return $noteGuid;
        } catch (EDAMNotFoundException $e) {
            print "Error stopping sharing note:";
            print var_dump($e);
        } catch (EDAMSystemException $e) {
            print "Error stopping sharing note:";
            print var_dump($e);
        } catch (EDAMUserException $e) {
            print "Error stopping sharing note:";
            print var_dump($e);
        }
        return null;
    }
    
    ?>
    example.java
    public String stopSharingSingleNote(NoteStoreClient noteStore, String noteGuid) {
      try {
        noteStore.stopSharingNote(noteGuid);
        return noteGuid;
      } catch (EDAMNotFoundException e) {
        System.out.println("Error stopping sharing note:");
        System.out.println(e);
      } catch (EDAMSystemException e) {
        System.out.println("Error stopping sharing note:");
        System.out.println(e);
      } catch (EDAMUserException e) {
        System.out.println("Error stopping sharing note:");
        System.out.println(e);
      } catch (TException e) {
        System.out.println("Error stopping sharing note:");
        System.out.println(e);
      }
      return null;
    }
    example.js
    function stopSharingSingleNote(noteStore, noteGuid, callback) {
      noteStore.stopSharingNote(noteGuid, function(obj) {
        if (obj && obj.errorCode) {
          console.log(obj);
        } else {
          callback(noteGuid);
        }
      });
    }
  • Listing All Shared Notes in an Account

    To search for all of the shared notes in a user’s account, we need to create a NoteFilter object and set its words member to sharedate:* (indicating that the note is shared and we don’t care when). Here’s a function that retrieves all of the shared notes in a user’s account (up to an arbitrary maximum of 500 notes):

    main.py
    def getAllSharedNotes(authToken, noteStore, maxCount=None):
    	noteFilter = NoteStore.NoteFilter()
    	noteFilter.words = "sharedate:*"
    	sharedNotes = []
    	offset = 0
    	if not maxCount:
    		maxCount = 500
    	while len(sharedNotes) < maxCount:
    		try:
    			noteList = noteStore.findNotes(authToken, noteFilter, offset, 50)
    			sharedNotes += noteList.notes
    		except (EDAMNotFoundException, EDAMSystemException, EDAMUserException), e:
    			print "Error getting shared notes:"
    			print type(e), e
    			return None
    
    		if len(sharedNotes) % 50 != 0:
    			## We've retrieved all of the notes 
    			break
    		else:
    			offset += 50
    	return sharedNotes[:maxCount]
    gistfile1.m
    - (void) getAllSharedNotes {
        EDAMNoteFilter *noteFilter = [[EDAMNoteFilter alloc] initWithOrder:0
                                                                 ascending:YES
                                                                     words:@"sharedate:*" notebookGuid:nil
                                                                  tagGuids:nil
                                                                  timeZone:nil
                                                                  inactive:NO
                                                                emphasized:nil];
        EDAMNotesMetadataResultSpec* metaDataResultSpec = [[EDAMNotesMetadataResultSpec alloc] initWithIncludeTitle:YES includeContentLength:YES includeCreated:NO includeUpdated:NO includeDeleted:NO includeUpdateSequenceNum:NO includeNotebookGuid:YES includeTagGuids:YES includeAttributes:YES includeLargestResourceMime:NO includeLargestResourceSize:NO];
        __block NSInteger i = 0;
        __block NSInteger totalNoteCount = 0;
        do {
            [[EvernoteNoteStore noteStore] findNotesMetadataWithFilter:noteFilter offset:i maxNotes:10 resultSpec:metaDataResultSpec success:^(EDAMNotesMetadataList *metadata) {
                NSLog(@"Shared notes metadata : %@",metadata);
                i += metadata.notes.count;
                totalNoteCount =  metadata.totalNotes;
            } failure:^(NSError *error) {
                NSLog(@"Error : %@",error);
            }];
        } while (i<totalNoteCount);
    }
    example.rb
    def get_all_shared_notes(note_store, max_count=nil)
      note_filter = Evernote::EDAM::NoteStore::NoteFilter.new
      note_filter.words = "sharedate:*"
      shared_notes = []
      offset = 0
      max_count ||= 500
      while shared_notes.length < max_count
        begin
          note_list = note_store.findNotes(note_filter, offset, 50)
          shared_notes += note_list.notes
        rescue Evernote::EDAM::Error::EDAMNotFoundException, Evernote::EDAM::Error::EDAMSystemException, Evernote::EDAM::Error::EDAMUserException => e
          puts "Error getting shared notes:"
          puts e.inspect
          return nil
        end
        if shared_notes.length % 50 != 0
          ## We've retrieved all of the notes 
          break
        else
          offset += 50
        end
      end
      shared_notes[0..max_count-1]
    end
    example.php
    <?php
    function getAllSharedNotes($noteStore, $maxCount = null) {
        $noteFilter = new NoteFilter();
        $noteFilter->words = "sharedate:*";
        $sharedNotes = array();
        $offset = 0;
        if ($maxCount == null) {
            $maxCount = 500;
        }
        while (count($sharedNotes) < $maxCount) {
            try {
                $noteList = $noteStore->findNotes($noteFilter, $offset, 50);
                $sharedNotes += $noteList->notes;
            } catch (EDAMNotFoundException $e) {
                print "Error getting shared notes:";
                var_dump($e);
                return null;
            } catch (EDAMSystemException $e) {
                print "Error getting shared notes:";
                var_dump($e);
                return null;
            } catch (EDAMUserException $e) {
                print "Error getting shared notes:";
                var_dump($e);
                return null;
            }
     
            if (count($sharedNotes) % 50 != 0) {
                // We've retrieved all of the notes 
                break;
            } else {
                $offset += 50;
            }
        }
        return array_slice($sharedNotes, 0, $maxCount);
    }
    ?>
    example.java
    public List<Note> getAllSharedNotes(NoteStoreClient noteStore, int maxCount) {
      NoteFilter noteFilter = new NoteFilter();
      noteFilter.setWords("sharedate:*");
      List<Note> sharedNotes = new ArrayList<Note>();
      int offset = 0;
      
      while (sharedNotes.size() < maxCount) {
        try {
          NoteList noteList = noteStore.findNotes(noteFilter, offset, 50);
          sharedNotes.addAll(noteList.getNotes());
        } catch (EDAMNotFoundException e) {
          System.out.println("Error getting shared notes:");
          System.out.println(e);
          return null;
        } catch (EDAMSystemException e) {
          System.out.println("Error getting shared notes:");
          System.out.println(e);
          return null;
        } catch (EDAMUserException e) {
          System.out.println("Error getting shared notes:");
          System.out.println(e);
          return null;
        } catch (TException e) {
          System.out.println("Error getting shared notes:");
          System.out.println(e);
          return null;
        }
     
        if (sharedNotes.size() % 50 != 0) {
          // We've retrieved all of the notes 
          break;
        } else {
          offset += 50;
        }
      }
      return sharedNotes.subList(0, Math.min(sharedNotes.size(), maxCount));
    }
    example.js
    function getAllSharedNotes(noteStore, maxCount, callback) {
      var noteFilter = new Evernote.NoteFilter();
      noteFilter.words = "sharedate:*";
      var sharedNotes = [];
      var offset = 0;
      if (!maxCount) {
        maxCount = 500;
      }
      (function _getAllSharedNotes(sharedNotes, offset, maxCount) {
        if (sharedNotes.length < maxCount) {
          noteStore.findNotes(noteFilter, offset, 50, function(noteList) {
            if (noteList.errorCode) {
              console.log("Error getting shared notes:");
              console.log(noteList);
              return;
            }
            sharedNotes = sharedNotes.concat(noteList.notes);
            if (sharedNotes.length % 50 != 0) {
              // We've retrieved all of the notes 
              callback(sharedNotes.slice(0, maxCount));
              return;
            } else {
              offset += 50;
              _getAllSharedNotes(sharedNotes, offset, maxCount);
            }
          });
        } else {
          callback(sharedNotes.slice(0, maxCount));
        }
      })(sharedNotes, offset, maxCount);
     
    }

    After creating and populating our NoteFilter instance, we repeatedly call NoteStore.findNotes, asking for 50 notes each time, collecting the responses into a sharedNotes collection. Once we hit our maximum number of notes or our sharedNotes collection is no longer evenly divisible by 50 (indicating that we received less than 50 notes during the most recent call to NoteStore.findNotes), we return sharedNotes.