SlideShare a Scribd company logo
1 of 39
Download to read offline
REST ing with 
the new 
Yandex.Disk API 
Clemens Auer 
Developer
What Is Yandex Disk?
What Is Yandex Disk? 
- 26 Million registered Disk users. 
- 6 Billion files. 
- 14 Million files added per day.
What Is Yandex Disk? 
How much storage space users get for free? 
- Basic: 10 GB. 
- Invites: up to 10 GB. 
- Partner offers: currently up to 50 GB.
What Is Yandex Disk? 
For those who need more: 
Storage 10 GB 100 GB 1 TB 
per month 30 RUB 150 RUB 900 RUB 
per year 300 RUB 1500 RUB 9000 RUB
What Is Yandex Disk? 
Clients 
- Web: disk.yandex.ru, widgets. 
- Desktop: Windows, Mac, Linux 
- Mobile: iOS, Android, WinPhone 
- 3rd party
What Is Yandex Disk? 
3rd party clients. 
- Official SDKs (JAVA, Obj-C, C#) 
- WebDAV + extensions 
- REST API
WebDAV vs. REST API
WebDAV vs. REST API 
WebDAV REST 
Upload ✓ ✓ 
Download ✓ ✓ 
Create Folder ✓ ✓ 
Copy ✓ ✓ 
Move ✓ ✓ 
Delete ✓ ✓ 
List ✓ ✓
WebDAV vs. REST API 
Support for public files 
WebDAV REST 
Share ✓ ✓ 
Unshare ✓ ✓ 
List Metadata ✗ ✓ 
Download ✗ ✓ 
Save to Disk ✗ ✓
WebDAV vs. REST API 
Working with the trash 
WebDAV REST 
List ✗ ✓ 
Delete ✗ ✓ 
Restore ✗ ✓
WebDAV vs. REST API 
What is missing? 
WebDAV REST 
Basic Auth ✓ ✗ 
Free/Used Space ✓ ✗* 
Hash Upload ✓ ✗ 
Custom Props ✓ ✗ 
Userinfo ✓ ✗
Getting Started 
- Register application 
- Register dev accounts 
- Get token for development 
- Полигон 
- Code
Register application
Register application
Register application
Register application
Register application
Register dev accounts.
https://oauth.yandex.ru/authorize?response_type=token&client_id= 
Get token for development
https://oauth.yandex.ru/verification_code?dev=True# 
access_token=d8edc4f3a698473fbc87634c41b2ca81 
&token_type=bearer 
&state= 
&expires_in=31536000 
Get token for development
Полигон
Getting Started 
- Register application 
- Register dev accounts 
- Get token for development 
- Полигон 
- Code
Code example 
What we try to achieve: 
import Foundation 
! 
public class Disk { 
… 
} 
! 
let disk = Disk(token: "d8edc4f3a698473fbc87634c41b2ca81") 
var fileURL : NSURL 
! 
disk.uploadURL(fileURL, toPath: fileURL.lastPathComponent, overwrite: true) { 
// handle errors 
} 
! 
disk.deletePath(fileURL.lastPathComponent, permanently: false) { 
// handle response 
}
Code example 
Basic properties in Disk class 
public class Disk { 
public let token : String 
public let baseURL = "https://cloud-api.yandex.net:443" 
! 
var additionalHTTPHeaders : [String:String] { 
return [ 
"Accept" : "application/json", 
"Authorization" : "OAuth (token)", 
"User-Agent" : "Mobile Camp Demo" 
] 
} 
}
Code example 
Complete basic Disk class 
public class Disk { 
public let token : String 
public let baseURL = "https://cloud-api.yandex.net:443" 
! 
var additionalHTTPHeaders : [String:String] { 
return [ 
"Accept" : "application/json", 
"Authorization" : "OAuth (token)", 
"User-Agent" : "Mobile Camp Demo" 
] 
} 
! 
public lazy var session : NSURLSession = { 
let config = NSURLSessionConfiguration.defaultSessionConfiguration() 
config.HTTPAdditionalHeaders = self.additionalHTTPHeaders 
! 
return NSURLSession(configuration: config) 
}() 
! 
public init(token:String) { 
self.token = token 
} 
}
Code example 
Disk extension for de-serializing JSON data 
extension Disk { 
class func JSONDictionaryWithData(data:NSData!, onError:(NSError!)->Void) 
-> NSDictionary? { 
! 
var error: NSError? 
let root = NSJSONSerialization.JSONObjectWithData(data, 
options: nil, error: &error) as? NSDictionary 
! 
if root == nil { 
onError(NSError(…)) 
return nil 
} 
! 
return root 
} 
}
Code example 
NSURLSessing extension for doing JSON requests 
extension NSURLSession { 
func jsonTaskWithMethod(method:String, url: NSURL!, onError: ((NSError!) -> Void)!, 
onCompletion: ((NSDictionary, NSHTTPURLResponse) -> Void)!) 
-> NSURLSessionDataTask! { 
! 
let request = NSMutableURLRequest(URL: url) 
request.HTTPMethod = method 
! 
return dataTaskWithRequest(request) { 
(data, response, error) -> Void in 
! 
let jsonRoot = Disk.JSONDictionaryWithData(data, onError: onError) 
! 
if let jsonRoot = jsonRoot { 
switch response.statusCode { 
case 400...599: 
return onError(…) 
default: 
return onCompletion(jsonRoot, response) 
} 
} else { 
return // handler already called from JSONDictionaryWithData 
} 
} 
} 
}
Take a peek at the documentation
Code example 
Disk extension for processing common JSON object 
extension Disk { 
class func hrefMethodTemplatedWithDictionary(dict:NSDictionary?) 
-> (href:String, method:String, templated:Bool) { 
var href = "" 
var method = "" 
var templated = false 
! 
if let json = dict { 
if let str = json["href"] as? String { 
href = str 
} 
if let str = json["method"] as? String { 
method = str 
} 
if let nr = json["templated"] as? NSNumber { 
templated = nr.boolValue 
} 
} 
! 
return (href, method, templated) 
} 
}
Code example 
Disk extension implementing file upload 
extension Disk { 
public func uploadURL(fileURL:NSURL, toPath path:String, overwrite:Bool?, 
handler:(NSError!) -> Void) -> Void { 
! 
var url = "(baseURL)/v1/disk/resources/upload?path=(path.urlEncoded())" 
! 
if let overwrite = overwrite { 
url += "&overwrite=(overwrite)" 
} 
let error = { handler($0) } 
! 
session.jsonTaskWithMethod("GET", url: NSURL(string: url), onError: error) { 
(jsonRoot, response)->Void in 
! 
let (href, method, templated) = Disk.hrefMethodTemplatedWithDictionary(jsonRoot) 
! 
let request = NSMutableURLRequest(URL: NSURL(string: href)) 
request.HTTPMethod = method 
! 
self.session.uploadTaskWithRequest(request, fromFile: fileURL) { 
(data, response, trasferError)->Void in 
! 
return error(trasferError) 
}.resume() 
}.resume() 
} 
}
Take another peek at the documentation
Code example 
Disk extension implementing delete. 
public enum DeletionResult { 
case Done 
case InProcess(href:String, method:String, templated:Bool) 
case Failed(NSError!) 
} 
! 
extension Disk { 
public func deletePath(path:String, permanently:Bool?, 
handler:(result:DeletionResult) -> Void) -> Void { 
var url = "(baseURL)/v1/disk/resources?path=(path.urlEncoded())" 
! 
if let permanently = permanently { 
url += "&permanently=(permanently)" 
} 
let error = { handler(result: .Failed($0)) } 
! 
session.jsonTaskWithMethod("DELETE", url: NSURL(string: url), onError: error) { 
(jsonRoot, response)->Void in 
switch response.statusCode { 
case 202: 
return handler(result: .InProcess(Disk.hrefMethodTemplatedWithDictionary(jsonRoot))) 
case 204: 
return handler(result: .Done) 
default: 
return error(NSError(…)) 
} 
}.resume() 
} }
Lessons Learned 
Swift 
- enum, switch, closures, tuples 
- Type safety vs. Obj-C weak typing 
- Volatile: Xcode release notes. 
- Apple Dev Forums
Lessons Learned 
REST API 
- Documentation vs. Полигон 
- Fast 
- OAuth 
- Roadmap ahead
Lessons Learned 
In general 
- Test driven development saves time. 
- Autotest the API version 
- Report bugs 
http://feedback2.yandex.ru/disk/api/
References 
https://oauth.yandex.ru 
https://oauth.yandex.ru/client/new 
http://api.yandex.ru/disk/ 
http://api.yandex.ru/login/ 
https://yadi.sk/d/5b9BoUjtZvJhp
Clemens Auer 
Developer 
aucl@yandex.ru 
aucl@yandex-team.ru 
Thank you

More Related Content

What's hot

Webinaire 2 de la série « Retour aux fondamentaux » : Votre première applicat...
Webinaire 2 de la série « Retour aux fondamentaux » : Votre première applicat...Webinaire 2 de la série « Retour aux fondamentaux » : Votre première applicat...
Webinaire 2 de la série « Retour aux fondamentaux » : Votre première applicat...MongoDB
 
C# Development (Sam Corder)
C# Development (Sam Corder)C# Development (Sam Corder)
C# Development (Sam Corder)MongoSF
 
Back to Basics Webinar 2: Your First MongoDB Application
Back to Basics Webinar 2: Your First MongoDB ApplicationBack to Basics Webinar 2: Your First MongoDB Application
Back to Basics Webinar 2: Your First MongoDB ApplicationMongoDB
 
Redis data modeling examples
Redis data modeling examplesRedis data modeling examples
Redis data modeling examplesTerry Cho
 
Redis for the Everyday Developer
Redis for the Everyday DeveloperRedis for the Everyday Developer
Redis for the Everyday DeveloperRoss Tuck
 
MongoDB Shell Tips & Tricks
MongoDB Shell Tips & TricksMongoDB Shell Tips & Tricks
MongoDB Shell Tips & TricksMongoDB
 
Top 10 F5 iRules to migrate to a modern load balancing platform
Top 10 F5 iRules to migrate to a modern load balancing platformTop 10 F5 iRules to migrate to a modern load balancing platform
Top 10 F5 iRules to migrate to a modern load balancing platformAvi Networks
 
Huong dan cai dat hadoop
Huong dan cai dat hadoopHuong dan cai dat hadoop
Huong dan cai dat hadoopQuỳnh Phan
 
Ch3(working with file)
Ch3(working with file)Ch3(working with file)
Ch3(working with file)Chhom Karath
 
Hands On Spring Data
Hands On Spring DataHands On Spring Data
Hands On Spring DataEric Bottard
 
MongoDB Performance Tuning
MongoDB Performance TuningMongoDB Performance Tuning
MongoDB Performance TuningPuneet Behl
 
PuppetCamp SEA @ Blk 71 - Nagios in under 10 mins with Puppet
PuppetCamp SEA @ Blk 71 -  Nagios in under 10 mins with PuppetPuppetCamp SEA @ Blk 71 -  Nagios in under 10 mins with Puppet
PuppetCamp SEA @ Blk 71 - Nagios in under 10 mins with PuppetOlinData
 
PuppetCamp SEA @ Blk 71 - Nagios in under 10 mins with Puppet
PuppetCamp SEA @ Blk 71 -  Nagios in under 10 mins with PuppetPuppetCamp SEA @ Blk 71 -  Nagios in under 10 mins with Puppet
PuppetCamp SEA @ Blk 71 - Nagios in under 10 mins with PuppetWalter Heck
 
Service intergration
Service intergration Service intergration
Service intergration 재민 장
 
JDD 2017: Nginx + Lua = OpenResty (Marcin Stożek)
JDD 2017: Nginx + Lua = OpenResty (Marcin Stożek)JDD 2017: Nginx + Lua = OpenResty (Marcin Stożek)
JDD 2017: Nginx + Lua = OpenResty (Marcin Stożek)PROIDEA
 
PuppetDB: A Single Source for Storing Your Puppet Data - PUG NY
PuppetDB: A Single Source for Storing Your Puppet Data - PUG NYPuppetDB: A Single Source for Storing Your Puppet Data - PUG NY
PuppetDB: A Single Source for Storing Your Puppet Data - PUG NYPuppet
 

What's hot (20)

Webinaire 2 de la série « Retour aux fondamentaux » : Votre première applicat...
Webinaire 2 de la série « Retour aux fondamentaux » : Votre première applicat...Webinaire 2 de la série « Retour aux fondamentaux » : Votre première applicat...
Webinaire 2 de la série « Retour aux fondamentaux » : Votre première applicat...
 
C# Development (Sam Corder)
C# Development (Sam Corder)C# Development (Sam Corder)
C# Development (Sam Corder)
 
Introduction to solr
Introduction to solrIntroduction to solr
Introduction to solr
 
Back to Basics Webinar 2: Your First MongoDB Application
Back to Basics Webinar 2: Your First MongoDB ApplicationBack to Basics Webinar 2: Your First MongoDB Application
Back to Basics Webinar 2: Your First MongoDB Application
 
Redis data modeling examples
Redis data modeling examplesRedis data modeling examples
Redis data modeling examples
 
Redis for the Everyday Developer
Redis for the Everyday DeveloperRedis for the Everyday Developer
Redis for the Everyday Developer
 
Python and MongoDB
Python and MongoDBPython and MongoDB
Python and MongoDB
 
MongoDB Shell Tips & Tricks
MongoDB Shell Tips & TricksMongoDB Shell Tips & Tricks
MongoDB Shell Tips & Tricks
 
Top 10 F5 iRules to migrate to a modern load balancing platform
Top 10 F5 iRules to migrate to a modern load balancing platformTop 10 F5 iRules to migrate to a modern load balancing platform
Top 10 F5 iRules to migrate to a modern load balancing platform
 
Huong dan cai dat hadoop
Huong dan cai dat hadoopHuong dan cai dat hadoop
Huong dan cai dat hadoop
 
Ch3(working with file)
Ch3(working with file)Ch3(working with file)
Ch3(working with file)
 
Hands On Spring Data
Hands On Spring DataHands On Spring Data
Hands On Spring Data
 
MongoDB Performance Tuning
MongoDB Performance TuningMongoDB Performance Tuning
MongoDB Performance Tuning
 
PuppetCamp SEA @ Blk 71 - Nagios in under 10 mins with Puppet
PuppetCamp SEA @ Blk 71 -  Nagios in under 10 mins with PuppetPuppetCamp SEA @ Blk 71 -  Nagios in under 10 mins with Puppet
PuppetCamp SEA @ Blk 71 - Nagios in under 10 mins with Puppet
 
PuppetCamp SEA @ Blk 71 - Nagios in under 10 mins with Puppet
PuppetCamp SEA @ Blk 71 -  Nagios in under 10 mins with PuppetPuppetCamp SEA @ Blk 71 -  Nagios in under 10 mins with Puppet
PuppetCamp SEA @ Blk 71 - Nagios in under 10 mins with Puppet
 
Service intergration
Service intergration Service intergration
Service intergration
 
JDD 2017: Nginx + Lua = OpenResty (Marcin Stożek)
JDD 2017: Nginx + Lua = OpenResty (Marcin Stożek)JDD 2017: Nginx + Lua = OpenResty (Marcin Stożek)
JDD 2017: Nginx + Lua = OpenResty (Marcin Stożek)
 
Elastic Search
Elastic SearchElastic Search
Elastic Search
 
PuppetDB: A Single Source for Storing Your Puppet Data - PUG NY
PuppetDB: A Single Source for Storing Your Puppet Data - PUG NYPuppetDB: A Single Source for Storing Your Puppet Data - PUG NY
PuppetDB: A Single Source for Storing Your Puppet Data - PUG NY
 
MongoDB - Ekino PHP
MongoDB - Ekino PHPMongoDB - Ekino PHP
MongoDB - Ekino PHP
 

Similar to RESTing with Yandex Disk API

Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...BradNeuberg
 
Express Presentation
Express PresentationExpress Presentation
Express Presentationaaronheckmann
 
Going crazy with Node.JS and CakePHP
Going crazy with Node.JS and CakePHPGoing crazy with Node.JS and CakePHP
Going crazy with Node.JS and CakePHPMariano Iglesias
 
Paris js extensions
Paris js extensionsParis js extensions
Paris js extensionserwanl
 
Intravert Server side processing for Cassandra
Intravert Server side processing for CassandraIntravert Server side processing for Cassandra
Intravert Server side processing for CassandraEdward Capriolo
 
NYC* 2013 - "Advanced Data Processing: Beyond Queries and Slices"
NYC* 2013 - "Advanced Data Processing: Beyond Queries and Slices"NYC* 2013 - "Advanced Data Processing: Beyond Queries and Slices"
NYC* 2013 - "Advanced Data Processing: Beyond Queries and Slices"DataStax Academy
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on AndroidSven Haiges
 
Elasticsearch sur Azure : Make sense of your (BIG) data !
Elasticsearch sur Azure : Make sense of your (BIG) data !Elasticsearch sur Azure : Make sense of your (BIG) data !
Elasticsearch sur Azure : Make sense of your (BIG) data !Microsoft
 
Make BDD great again
Make BDD great againMake BDD great again
Make BDD great againYana Gusti
 
Web program-peformance-optimization
Web program-peformance-optimizationWeb program-peformance-optimization
Web program-peformance-optimizationxiaojueqq12345
 
Build web application by express
Build web application by expressBuild web application by express
Build web application by expressShawn Meng
 
Java script at backend nodejs
Java script at backend   nodejsJava script at backend   nodejs
Java script at backend nodejsAmit Thakkar
 
Cross Domain Web
Mashups with JQuery and Google App Engine
Cross Domain Web
Mashups with JQuery and Google App EngineCross Domain Web
Mashups with JQuery and Google App Engine
Cross Domain Web
Mashups with JQuery and Google App EngineAndy McKay
 
Google apps script database abstraction exposed version
Google apps script database abstraction   exposed versionGoogle apps script database abstraction   exposed version
Google apps script database abstraction exposed versionBruce McPherson
 
Zendcon 2007 Api Design
Zendcon 2007 Api DesignZendcon 2007 Api Design
Zendcon 2007 Api Designunodelostrece
 
Using and scaling Rack and Rack-based middleware
Using and scaling Rack and Rack-based middlewareUsing and scaling Rack and Rack-based middleware
Using and scaling Rack and Rack-based middlewareAlona Mekhovova
 
Node.js - async for the rest of us.
Node.js - async for the rest of us.Node.js - async for the rest of us.
Node.js - async for the rest of us.Mike Brevoort
 

Similar to RESTing with Yandex Disk API (20)

Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
 
Express Presentation
Express PresentationExpress Presentation
Express Presentation
 
Going crazy with Node.JS and CakePHP
Going crazy with Node.JS and CakePHPGoing crazy with Node.JS and CakePHP
Going crazy with Node.JS and CakePHP
 
Paris js extensions
Paris js extensionsParis js extensions
Paris js extensions
 
Node.js - A Quick Tour
Node.js - A Quick TourNode.js - A Quick Tour
Node.js - A Quick Tour
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Intravert Server side processing for Cassandra
Intravert Server side processing for CassandraIntravert Server side processing for Cassandra
Intravert Server side processing for Cassandra
 
NYC* 2013 - "Advanced Data Processing: Beyond Queries and Slices"
NYC* 2013 - "Advanced Data Processing: Beyond Queries and Slices"NYC* 2013 - "Advanced Data Processing: Beyond Queries and Slices"
NYC* 2013 - "Advanced Data Processing: Beyond Queries and Slices"
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on Android
 
Elasticsearch sur Azure : Make sense of your (BIG) data !
Elasticsearch sur Azure : Make sense of your (BIG) data !Elasticsearch sur Azure : Make sense of your (BIG) data !
Elasticsearch sur Azure : Make sense of your (BIG) data !
 
Make BDD great again
Make BDD great againMake BDD great again
Make BDD great again
 
Web program-peformance-optimization
Web program-peformance-optimizationWeb program-peformance-optimization
Web program-peformance-optimization
 
Build web application by express
Build web application by expressBuild web application by express
Build web application by express
 
Java script at backend nodejs
Java script at backend   nodejsJava script at backend   nodejs
Java script at backend nodejs
 
Os Pruett
Os PruettOs Pruett
Os Pruett
 
Cross Domain Web
Mashups with JQuery and Google App Engine
Cross Domain Web
Mashups with JQuery and Google App EngineCross Domain Web
Mashups with JQuery and Google App Engine
Cross Domain Web
Mashups with JQuery and Google App Engine
 
Google apps script database abstraction exposed version
Google apps script database abstraction   exposed versionGoogle apps script database abstraction   exposed version
Google apps script database abstraction exposed version
 
Zendcon 2007 Api Design
Zendcon 2007 Api DesignZendcon 2007 Api Design
Zendcon 2007 Api Design
 
Using and scaling Rack and Rack-based middleware
Using and scaling Rack and Rack-based middlewareUsing and scaling Rack and Rack-based middleware
Using and scaling Rack and Rack-based middleware
 
Node.js - async for the rest of us.
Node.js - async for the rest of us.Node.js - async for the rest of us.
Node.js - async for the rest of us.
 

More from Yandex

Предсказание оттока игроков из World of Tanks
Предсказание оттока игроков из World of TanksПредсказание оттока игроков из World of Tanks
Предсказание оттока игроков из World of TanksYandex
 
Как принять/организовать работу по поисковой оптимизации сайта, Сергей Царик,...
Как принять/организовать работу по поисковой оптимизации сайта, Сергей Царик,...Как принять/организовать работу по поисковой оптимизации сайта, Сергей Царик,...
Как принять/организовать работу по поисковой оптимизации сайта, Сергей Царик,...Yandex
 
Структурированные данные, Юлия Тихоход, лекция в Школе вебмастеров Яндекса
Структурированные данные, Юлия Тихоход, лекция в Школе вебмастеров ЯндексаСтруктурированные данные, Юлия Тихоход, лекция в Школе вебмастеров Яндекса
Структурированные данные, Юлия Тихоход, лекция в Школе вебмастеров ЯндексаYandex
 
Представление сайта в поиске, Сергей Лысенко, лекция в Школе вебмастеров Яндекса
Представление сайта в поиске, Сергей Лысенко, лекция в Школе вебмастеров ЯндексаПредставление сайта в поиске, Сергей Лысенко, лекция в Школе вебмастеров Яндекса
Представление сайта в поиске, Сергей Лысенко, лекция в Школе вебмастеров ЯндексаYandex
 
Плохие методы продвижения сайта, Екатерины Гладких, лекция в Школе вебмастеро...
Плохие методы продвижения сайта, Екатерины Гладких, лекция в Школе вебмастеро...Плохие методы продвижения сайта, Екатерины Гладких, лекция в Школе вебмастеро...
Плохие методы продвижения сайта, Екатерины Гладких, лекция в Школе вебмастеро...Yandex
 
Основные принципы ранжирования, Сергей Царик и Антон Роменский, лекция в Школ...
Основные принципы ранжирования, Сергей Царик и Антон Роменский, лекция в Школ...Основные принципы ранжирования, Сергей Царик и Антон Роменский, лекция в Школ...
Основные принципы ранжирования, Сергей Царик и Антон Роменский, лекция в Школ...Yandex
 
Основные принципы индексирования сайта, Александр Смирнов, лекция в Школе веб...
Основные принципы индексирования сайта, Александр Смирнов, лекция в Школе веб...Основные принципы индексирования сайта, Александр Смирнов, лекция в Школе веб...
Основные принципы индексирования сайта, Александр Смирнов, лекция в Школе веб...Yandex
 
Мобильное приложение: как и зачем, Александр Лукин, лекция в Школе вебмастеро...
Мобильное приложение: как и зачем, Александр Лукин, лекция в Школе вебмастеро...Мобильное приложение: как и зачем, Александр Лукин, лекция в Школе вебмастеро...
Мобильное приложение: как и зачем, Александр Лукин, лекция в Школе вебмастеро...Yandex
 
Сайты на мобильных устройствах, Олег Ножичкин, лекция в Школе вебмастеров Янд...
Сайты на мобильных устройствах, Олег Ножичкин, лекция в Школе вебмастеров Янд...Сайты на мобильных устройствах, Олег Ножичкин, лекция в Школе вебмастеров Янд...
Сайты на мобильных устройствах, Олег Ножичкин, лекция в Школе вебмастеров Янд...Yandex
 
Качественная аналитика сайта, Юрий Батиевский, лекция в Школе вебмастеров Янд...
Качественная аналитика сайта, Юрий Батиевский, лекция в Школе вебмастеров Янд...Качественная аналитика сайта, Юрий Батиевский, лекция в Школе вебмастеров Янд...
Качественная аналитика сайта, Юрий Батиевский, лекция в Школе вебмастеров Янд...Yandex
 
Что можно и что нужно измерять на сайте, Петр Аброськин, лекция в Школе вебма...
Что можно и что нужно измерять на сайте, Петр Аброськин, лекция в Школе вебма...Что можно и что нужно измерять на сайте, Петр Аброськин, лекция в Школе вебма...
Что можно и что нужно измерять на сайте, Петр Аброськин, лекция в Школе вебма...Yandex
 
Как правильно поставить ТЗ на создание сайта, Алексей Бородкин, лекция в Школ...
Как правильно поставить ТЗ на создание сайта, Алексей Бородкин, лекция в Школ...Как правильно поставить ТЗ на создание сайта, Алексей Бородкин, лекция в Школ...
Как правильно поставить ТЗ на создание сайта, Алексей Бородкин, лекция в Школ...Yandex
 
Как защитить свой сайт, Пётр Волков, лекция в Школе вебмастеров
Как защитить свой сайт, Пётр Волков, лекция в Школе вебмастеровКак защитить свой сайт, Пётр Волков, лекция в Школе вебмастеров
Как защитить свой сайт, Пётр Волков, лекция в Школе вебмастеровYandex
 
Как правильно составить структуру сайта, Дмитрий Сатин, лекция в Школе вебмас...
Как правильно составить структуру сайта, Дмитрий Сатин, лекция в Школе вебмас...Как правильно составить структуру сайта, Дмитрий Сатин, лекция в Школе вебмас...
Как правильно составить структуру сайта, Дмитрий Сатин, лекция в Школе вебмас...Yandex
 
Технические особенности создания сайта, Дмитрий Васильева, лекция в Школе веб...
Технические особенности создания сайта, Дмитрий Васильева, лекция в Школе веб...Технические особенности создания сайта, Дмитрий Васильева, лекция в Школе веб...
Технические особенности создания сайта, Дмитрий Васильева, лекция в Школе веб...Yandex
 
Конструкторы для отдельных элементов сайта, Елена Першина, лекция в Школе веб...
Конструкторы для отдельных элементов сайта, Елена Першина, лекция в Школе веб...Конструкторы для отдельных элементов сайта, Елена Першина, лекция в Школе веб...
Конструкторы для отдельных элементов сайта, Елена Першина, лекция в Школе веб...Yandex
 
Контент для интернет-магазинов, Катерина Ерошина, лекция в Школе вебмастеров ...
Контент для интернет-магазинов, Катерина Ерошина, лекция в Школе вебмастеров ...Контент для интернет-магазинов, Катерина Ерошина, лекция в Школе вебмастеров ...
Контент для интернет-магазинов, Катерина Ерошина, лекция в Школе вебмастеров ...Yandex
 
Как написать хороший текст для сайта, Катерина Ерошина, лекция в Школе вебмас...
Как написать хороший текст для сайта, Катерина Ерошина, лекция в Школе вебмас...Как написать хороший текст для сайта, Катерина Ерошина, лекция в Школе вебмас...
Как написать хороший текст для сайта, Катерина Ерошина, лекция в Школе вебмас...Yandex
 
Usability и дизайн - как не помешать пользователю, Алексей Иванов, лекция в Ш...
Usability и дизайн - как не помешать пользователю, Алексей Иванов, лекция в Ш...Usability и дизайн - как не помешать пользователю, Алексей Иванов, лекция в Ш...
Usability и дизайн - как не помешать пользователю, Алексей Иванов, лекция в Ш...Yandex
 
Cайт. Зачем он и каким должен быть, Алексей Иванов, лекция в Школе вебмастеро...
Cайт. Зачем он и каким должен быть, Алексей Иванов, лекция в Школе вебмастеро...Cайт. Зачем он и каким должен быть, Алексей Иванов, лекция в Школе вебмастеро...
Cайт. Зачем он и каким должен быть, Алексей Иванов, лекция в Школе вебмастеро...Yandex
 

More from Yandex (20)

Предсказание оттока игроков из World of Tanks
Предсказание оттока игроков из World of TanksПредсказание оттока игроков из World of Tanks
Предсказание оттока игроков из World of Tanks
 
Как принять/организовать работу по поисковой оптимизации сайта, Сергей Царик,...
Как принять/организовать работу по поисковой оптимизации сайта, Сергей Царик,...Как принять/организовать работу по поисковой оптимизации сайта, Сергей Царик,...
Как принять/организовать работу по поисковой оптимизации сайта, Сергей Царик,...
 
Структурированные данные, Юлия Тихоход, лекция в Школе вебмастеров Яндекса
Структурированные данные, Юлия Тихоход, лекция в Школе вебмастеров ЯндексаСтруктурированные данные, Юлия Тихоход, лекция в Школе вебмастеров Яндекса
Структурированные данные, Юлия Тихоход, лекция в Школе вебмастеров Яндекса
 
Представление сайта в поиске, Сергей Лысенко, лекция в Школе вебмастеров Яндекса
Представление сайта в поиске, Сергей Лысенко, лекция в Школе вебмастеров ЯндексаПредставление сайта в поиске, Сергей Лысенко, лекция в Школе вебмастеров Яндекса
Представление сайта в поиске, Сергей Лысенко, лекция в Школе вебмастеров Яндекса
 
Плохие методы продвижения сайта, Екатерины Гладких, лекция в Школе вебмастеро...
Плохие методы продвижения сайта, Екатерины Гладких, лекция в Школе вебмастеро...Плохие методы продвижения сайта, Екатерины Гладких, лекция в Школе вебмастеро...
Плохие методы продвижения сайта, Екатерины Гладких, лекция в Школе вебмастеро...
 
Основные принципы ранжирования, Сергей Царик и Антон Роменский, лекция в Школ...
Основные принципы ранжирования, Сергей Царик и Антон Роменский, лекция в Школ...Основные принципы ранжирования, Сергей Царик и Антон Роменский, лекция в Школ...
Основные принципы ранжирования, Сергей Царик и Антон Роменский, лекция в Школ...
 
Основные принципы индексирования сайта, Александр Смирнов, лекция в Школе веб...
Основные принципы индексирования сайта, Александр Смирнов, лекция в Школе веб...Основные принципы индексирования сайта, Александр Смирнов, лекция в Школе веб...
Основные принципы индексирования сайта, Александр Смирнов, лекция в Школе веб...
 
Мобильное приложение: как и зачем, Александр Лукин, лекция в Школе вебмастеро...
Мобильное приложение: как и зачем, Александр Лукин, лекция в Школе вебмастеро...Мобильное приложение: как и зачем, Александр Лукин, лекция в Школе вебмастеро...
Мобильное приложение: как и зачем, Александр Лукин, лекция в Школе вебмастеро...
 
Сайты на мобильных устройствах, Олег Ножичкин, лекция в Школе вебмастеров Янд...
Сайты на мобильных устройствах, Олег Ножичкин, лекция в Школе вебмастеров Янд...Сайты на мобильных устройствах, Олег Ножичкин, лекция в Школе вебмастеров Янд...
Сайты на мобильных устройствах, Олег Ножичкин, лекция в Школе вебмастеров Янд...
 
Качественная аналитика сайта, Юрий Батиевский, лекция в Школе вебмастеров Янд...
Качественная аналитика сайта, Юрий Батиевский, лекция в Школе вебмастеров Янд...Качественная аналитика сайта, Юрий Батиевский, лекция в Школе вебмастеров Янд...
Качественная аналитика сайта, Юрий Батиевский, лекция в Школе вебмастеров Янд...
 
Что можно и что нужно измерять на сайте, Петр Аброськин, лекция в Школе вебма...
Что можно и что нужно измерять на сайте, Петр Аброськин, лекция в Школе вебма...Что можно и что нужно измерять на сайте, Петр Аброськин, лекция в Школе вебма...
Что можно и что нужно измерять на сайте, Петр Аброськин, лекция в Школе вебма...
 
Как правильно поставить ТЗ на создание сайта, Алексей Бородкин, лекция в Школ...
Как правильно поставить ТЗ на создание сайта, Алексей Бородкин, лекция в Школ...Как правильно поставить ТЗ на создание сайта, Алексей Бородкин, лекция в Школ...
Как правильно поставить ТЗ на создание сайта, Алексей Бородкин, лекция в Школ...
 
Как защитить свой сайт, Пётр Волков, лекция в Школе вебмастеров
Как защитить свой сайт, Пётр Волков, лекция в Школе вебмастеровКак защитить свой сайт, Пётр Волков, лекция в Школе вебмастеров
Как защитить свой сайт, Пётр Волков, лекция в Школе вебмастеров
 
Как правильно составить структуру сайта, Дмитрий Сатин, лекция в Школе вебмас...
Как правильно составить структуру сайта, Дмитрий Сатин, лекция в Школе вебмас...Как правильно составить структуру сайта, Дмитрий Сатин, лекция в Школе вебмас...
Как правильно составить структуру сайта, Дмитрий Сатин, лекция в Школе вебмас...
 
Технические особенности создания сайта, Дмитрий Васильева, лекция в Школе веб...
Технические особенности создания сайта, Дмитрий Васильева, лекция в Школе веб...Технические особенности создания сайта, Дмитрий Васильева, лекция в Школе веб...
Технические особенности создания сайта, Дмитрий Васильева, лекция в Школе веб...
 
Конструкторы для отдельных элементов сайта, Елена Першина, лекция в Школе веб...
Конструкторы для отдельных элементов сайта, Елена Першина, лекция в Школе веб...Конструкторы для отдельных элементов сайта, Елена Першина, лекция в Школе веб...
Конструкторы для отдельных элементов сайта, Елена Першина, лекция в Школе веб...
 
Контент для интернет-магазинов, Катерина Ерошина, лекция в Школе вебмастеров ...
Контент для интернет-магазинов, Катерина Ерошина, лекция в Школе вебмастеров ...Контент для интернет-магазинов, Катерина Ерошина, лекция в Школе вебмастеров ...
Контент для интернет-магазинов, Катерина Ерошина, лекция в Школе вебмастеров ...
 
Как написать хороший текст для сайта, Катерина Ерошина, лекция в Школе вебмас...
Как написать хороший текст для сайта, Катерина Ерошина, лекция в Школе вебмас...Как написать хороший текст для сайта, Катерина Ерошина, лекция в Школе вебмас...
Как написать хороший текст для сайта, Катерина Ерошина, лекция в Школе вебмас...
 
Usability и дизайн - как не помешать пользователю, Алексей Иванов, лекция в Ш...
Usability и дизайн - как не помешать пользователю, Алексей Иванов, лекция в Ш...Usability и дизайн - как не помешать пользователю, Алексей Иванов, лекция в Ш...
Usability и дизайн - как не помешать пользователю, Алексей Иванов, лекция в Ш...
 
Cайт. Зачем он и каким должен быть, Алексей Иванов, лекция в Школе вебмастеро...
Cайт. Зачем он и каким должен быть, Алексей Иванов, лекция в Школе вебмастеро...Cайт. Зачем он и каким должен быть, Алексей Иванов, лекция в Школе вебмастеро...
Cайт. Зачем он и каким должен быть, Алексей Иванов, лекция в Школе вебмастеро...
 

Recently uploaded

Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 

Recently uploaded (20)

Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 

RESTing with Yandex Disk API

  • 1.
  • 2. REST ing with the new Yandex.Disk API Clemens Auer Developer
  • 4. What Is Yandex Disk? - 26 Million registered Disk users. - 6 Billion files. - 14 Million files added per day.
  • 5. What Is Yandex Disk? How much storage space users get for free? - Basic: 10 GB. - Invites: up to 10 GB. - Partner offers: currently up to 50 GB.
  • 6. What Is Yandex Disk? For those who need more: Storage 10 GB 100 GB 1 TB per month 30 RUB 150 RUB 900 RUB per year 300 RUB 1500 RUB 9000 RUB
  • 7. What Is Yandex Disk? Clients - Web: disk.yandex.ru, widgets. - Desktop: Windows, Mac, Linux - Mobile: iOS, Android, WinPhone - 3rd party
  • 8. What Is Yandex Disk? 3rd party clients. - Official SDKs (JAVA, Obj-C, C#) - WebDAV + extensions - REST API
  • 10. WebDAV vs. REST API WebDAV REST Upload ✓ ✓ Download ✓ ✓ Create Folder ✓ ✓ Copy ✓ ✓ Move ✓ ✓ Delete ✓ ✓ List ✓ ✓
  • 11. WebDAV vs. REST API Support for public files WebDAV REST Share ✓ ✓ Unshare ✓ ✓ List Metadata ✗ ✓ Download ✗ ✓ Save to Disk ✗ ✓
  • 12. WebDAV vs. REST API Working with the trash WebDAV REST List ✗ ✓ Delete ✗ ✓ Restore ✗ ✓
  • 13. WebDAV vs. REST API What is missing? WebDAV REST Basic Auth ✓ ✗ Free/Used Space ✓ ✗* Hash Upload ✓ ✗ Custom Props ✓ ✗ Userinfo ✓ ✗
  • 14. Getting Started - Register application - Register dev accounts - Get token for development - Полигон - Code
  • 24. Getting Started - Register application - Register dev accounts - Get token for development - Полигон - Code
  • 25. Code example What we try to achieve: import Foundation ! public class Disk { … } ! let disk = Disk(token: "d8edc4f3a698473fbc87634c41b2ca81") var fileURL : NSURL ! disk.uploadURL(fileURL, toPath: fileURL.lastPathComponent, overwrite: true) { // handle errors } ! disk.deletePath(fileURL.lastPathComponent, permanently: false) { // handle response }
  • 26. Code example Basic properties in Disk class public class Disk { public let token : String public let baseURL = "https://cloud-api.yandex.net:443" ! var additionalHTTPHeaders : [String:String] { return [ "Accept" : "application/json", "Authorization" : "OAuth (token)", "User-Agent" : "Mobile Camp Demo" ] } }
  • 27. Code example Complete basic Disk class public class Disk { public let token : String public let baseURL = "https://cloud-api.yandex.net:443" ! var additionalHTTPHeaders : [String:String] { return [ "Accept" : "application/json", "Authorization" : "OAuth (token)", "User-Agent" : "Mobile Camp Demo" ] } ! public lazy var session : NSURLSession = { let config = NSURLSessionConfiguration.defaultSessionConfiguration() config.HTTPAdditionalHeaders = self.additionalHTTPHeaders ! return NSURLSession(configuration: config) }() ! public init(token:String) { self.token = token } }
  • 28. Code example Disk extension for de-serializing JSON data extension Disk { class func JSONDictionaryWithData(data:NSData!, onError:(NSError!)->Void) -> NSDictionary? { ! var error: NSError? let root = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &error) as? NSDictionary ! if root == nil { onError(NSError(…)) return nil } ! return root } }
  • 29. Code example NSURLSessing extension for doing JSON requests extension NSURLSession { func jsonTaskWithMethod(method:String, url: NSURL!, onError: ((NSError!) -> Void)!, onCompletion: ((NSDictionary, NSHTTPURLResponse) -> Void)!) -> NSURLSessionDataTask! { ! let request = NSMutableURLRequest(URL: url) request.HTTPMethod = method ! return dataTaskWithRequest(request) { (data, response, error) -> Void in ! let jsonRoot = Disk.JSONDictionaryWithData(data, onError: onError) ! if let jsonRoot = jsonRoot { switch response.statusCode { case 400...599: return onError(…) default: return onCompletion(jsonRoot, response) } } else { return // handler already called from JSONDictionaryWithData } } } }
  • 30. Take a peek at the documentation
  • 31. Code example Disk extension for processing common JSON object extension Disk { class func hrefMethodTemplatedWithDictionary(dict:NSDictionary?) -> (href:String, method:String, templated:Bool) { var href = "" var method = "" var templated = false ! if let json = dict { if let str = json["href"] as? String { href = str } if let str = json["method"] as? String { method = str } if let nr = json["templated"] as? NSNumber { templated = nr.boolValue } } ! return (href, method, templated) } }
  • 32. Code example Disk extension implementing file upload extension Disk { public func uploadURL(fileURL:NSURL, toPath path:String, overwrite:Bool?, handler:(NSError!) -> Void) -> Void { ! var url = "(baseURL)/v1/disk/resources/upload?path=(path.urlEncoded())" ! if let overwrite = overwrite { url += "&overwrite=(overwrite)" } let error = { handler($0) } ! session.jsonTaskWithMethod("GET", url: NSURL(string: url), onError: error) { (jsonRoot, response)->Void in ! let (href, method, templated) = Disk.hrefMethodTemplatedWithDictionary(jsonRoot) ! let request = NSMutableURLRequest(URL: NSURL(string: href)) request.HTTPMethod = method ! self.session.uploadTaskWithRequest(request, fromFile: fileURL) { (data, response, trasferError)->Void in ! return error(trasferError) }.resume() }.resume() } }
  • 33. Take another peek at the documentation
  • 34. Code example Disk extension implementing delete. public enum DeletionResult { case Done case InProcess(href:String, method:String, templated:Bool) case Failed(NSError!) } ! extension Disk { public func deletePath(path:String, permanently:Bool?, handler:(result:DeletionResult) -> Void) -> Void { var url = "(baseURL)/v1/disk/resources?path=(path.urlEncoded())" ! if let permanently = permanently { url += "&permanently=(permanently)" } let error = { handler(result: .Failed($0)) } ! session.jsonTaskWithMethod("DELETE", url: NSURL(string: url), onError: error) { (jsonRoot, response)->Void in switch response.statusCode { case 202: return handler(result: .InProcess(Disk.hrefMethodTemplatedWithDictionary(jsonRoot))) case 204: return handler(result: .Done) default: return error(NSError(…)) } }.resume() } }
  • 35. Lessons Learned Swift - enum, switch, closures, tuples - Type safety vs. Obj-C weak typing - Volatile: Xcode release notes. - Apple Dev Forums
  • 36. Lessons Learned REST API - Documentation vs. Полигон - Fast - OAuth - Roadmap ahead
  • 37. Lessons Learned In general - Test driven development saves time. - Autotest the API version - Report bugs http://feedback2.yandex.ru/disk/api/
  • 38. References https://oauth.yandex.ru https://oauth.yandex.ru/client/new http://api.yandex.ru/disk/ http://api.yandex.ru/login/ https://yadi.sk/d/5b9BoUjtZvJhp
  • 39. Clemens Auer Developer aucl@yandex.ru aucl@yandex-team.ru Thank you