SlideShare a Scribd company logo
Design Web 
Service API 
Arabnet 2014 Riyadh
Hossein 
Bukhamseen 
HungerStation.com
Design Web Service API by HungerStation
What 
Application Programming Interface
What 
● CORBA 
● Ice 
● SOAP 
● REST
Debates 
● Binary over TCP: Performance 
○ APN 
● Text over HTTP: Flexibility 
● Verbose 
● Strict
Programmer 
Interface 
They’ll judge you by your API
Why 
Let other programmers build on top of your service
Why 
● Mobile applications 
● Exposure 
● Integration with third party services 
● Technical 
○ Abstraction 
○ Simplicity 
● Everyone else has API!
How
SOAP 
Simple Object Access protocol
REST 
Representational state transfer
source(2014-11-10) : http://www.google.com/trends/explore#q=%2Fm%2F077dn%2C%20%2Fm%2F03nsxd&cmpt=q
HTTP
Explaining HTTP
image source: https://www.dartlang.org/docs/tutorials/fetchdata/
HTTP Request 
GET /books HTTP/1.1 
User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT) 
Host: www.example.com 
Accept-Language: en-us 
Accept-Encoding: gzip, deflate 
Connection: Keep-Alive
HTTP Request Method 
GET /books HTTP/1.1 
User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT) 
Host: www.example.com 
Accept-Language: en-us 
Accept-Encoding: gzip, deflate 
Connection: Keep-Alive
HTTP Request Resource 
GET /books HTTP/1.1 
User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT) 
Host: www.example.com 
Accept-Language: en-us 
Accept-Encoding: gzip, deflate 
Connection: Keep-Alive
HTTP Request Headers 
GET /books HTTP/1.1 
User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT) 
Host: www.example.com 
Accept-Language: en-us 
Accept-Encoding: gzip, deflate 
Connection: Keep-Alive
HTTP Request Payload 
POST /books HTTP/1.1 
User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT) 
Host: www.example.com 
Content-Type: application/x-www-form-urlencoded 
Content-Length: length 
Accept-Language: en-us 
Accept-Encoding: gzip, deflate 
Connection: Keep-Alive 
name=The+Hitchhiker% 
27s+Guide+to+the+Galaxy&author=Douglas+Adams
HTTP Verb 
● GET 
● POST 
● PUT/PATCH 
● DELETE
Resource 
● Model 
● Date element 
● URL 
● /books 
● /books/1
Request Headers 
● explain the request 
● predefined headers 
○ Accept-Language, Accept, Content-Encoding, User- 
Agent, Referer, Authorization, ... 
● Custom headers 
○ X-Pjax-C, X-Proto, X-Forwarded-For
Request Payload 
● Data 
● Content-Type 
● File
GET 
Read data
GET /books/1 HTTP/1.1 
User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT) 
Host: www.example.com 
Accept-Language: en-us 
Accept-Encoding: gzip, deflate 
Connection: Keep-Alive 
select * from books where id=1;
POST 
Create a new model
POST /books HTTP/1.1 
User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT) 
Host: www.example.com 
Content-Type: application/x-www-form-urlencoded 
Content-Length: length 
Accept-Language: en-us 
Accept-Encoding: gzip, deflate 
Connection: Keep-Alive 
name=The+Hitchhiker%27s+Guide+to+the+Galaxy&author=Douglas+Adams 
insert into books (name, author) values (‘The Hitchhiker's Guide to the Galaxy’,’ 
Douglas Adams’);
PUT/PATCH 
Modify a model
PATCH /books/1 HTTP/1.1 
User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT) 
Host: www.example.com 
Content-Type: application/x-www-form-urlencoded 
Content-Length: length 
Accept-Language: en-us 
Accept-Encoding: gzip, deflate 
Connection: Keep-Alive 
published=true 
update books set published=true;
DELETE 
Remove a resource
DELETE /books/1 HTTP/1.1 
User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT) 
Host: www.example.com 
Accept-Language: en-us 
Accept-Encoding: gzip, deflate 
Connection: Keep-Alive 
delete from books where id=1;
Create HTTP Request
Objective C (iOS) 
//create a reusable session 
NSURLSessionConfiguration* sessionConfiguration; 
NSURLSession *session; 
sessionConfiguration=[NSURLSessionConfiguration defaultSessionConfiguration]; 
[sessionConfiguration setHTTPAdditionalHeaders: 
@{@"Accept":@"application/json"}]; 
session=[NSURLSession sessionWithConfiguration:sessionConfiguration]; 
//execute the request 
NSURL* url=[NSURL URLWithString:@"https://secure-escarpment-9317.herokuapp.com/books.json"]; 
NSURLSessionDataTask* task=[session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse 
*response, NSError *error) { 
ا// handling response 
}]; 
[task resume];
HTTP Response 
HTTP/1.1 200 OK 
Content-Type:application/json; charset=utf-8 
Date:Mon, 10 Nov 2014 06:42:57 GMT 
Server:nginx/1.6.2 
Content-Length: 72 
Connection: keep-alive 
{"name": "The Hitchhiker's Guide to the Galaxy",author: "Douglas Adams"}
Status 
HTTP/1.1 200 OK 
Content-Type:application/json; charset=utf-8 
Date:Mon, 10 Nov 2014 06:42:57 GMT 
Server:nginx/1.6.2 
Content-Length: 72 
Connection: keep-alive 
{"name": "The Hitchhiker's Guide to the Galaxy",author: "Douglas Adams"}
Headers 
HTTP/1.1 200 OK 
Content-Type:application/json; charset=utf-8 
Date:Mon, 10 Nov 2014 06:42:57 GMT 
Server:nginx/1.6.2 
Content-Length: 72 
Connection: keep-alive 
{"name": "The Hitchhiker's Guide to the Galaxy",author: "Douglas Adams"}
Content 
HTTP/1.1 200 OK 
Content-Type:application/json; charset=utf-8 
Date:Mon, 10 Nov 2014 06:42:57 GMT 
Server:nginx/1.6.2 
Content-Length: 79 
Connection: keep-alive 
{"name": "The Hitchhiker's Guide to the Galaxy",author: "Douglas 
Adams",”id”:1}
Status Codes 
2XX OK 
3XX Redirection 
4XX Client Error 
5XX Server Error
2XX Successful Codes 
200 Successful 
201 Created 
202 Accepted 
204 No Content 
206 Partial Content
3XX Redirect Codes 
301 Permanently 
301 Temporary
4XX Client Error Codes 
400 Bad Request 
401 Unauthorized 
403 Forbidden 
404 No Found 
422 Unprocessable entity
5XX Server Error Codes 
500 Internal Server Error 
501 Service Unavailable
HTTP Response Headers 
● Explain response 
● Required headers 
● Standard headers 
● Custom headers
HTTP Response Content 
{ 
"id": 3, 
"title": "The Hitchhiker's Guide to the Galaxy", 
"author": "Douglas Adams", 
"published": false, 
"created_at": "2014-11-10T13:39:24.894Z", 
"updated_at": "2014-11-10T13:39:24.894Z" 
}
Create Response Example 
# POST /books 
# POST /books.json 
def create 
@book = Book.new(book_params) 
respond_to do |format| 
if @book.save 
format.html { redirect_to @book, notice: 'Book was successfully created.' } 
format.json { render :show, status: :created, location: @book } 
else 
format.html { render :new } 
format.json { render json: @book.errors, status: :unprocessable_entity } 
end 
end 
end
Create Response Example 
public function create() 
{ 
$book = new Book; 
$book->title = Request::get('title'); 
$book->author = Request::get('author'); 
$book->save(); 
return Response::json(array( 
'error' => false, 
'urls' => $urls->toArray()), 
201 
); 
}
REST
Client–server 
● Separation of concerns 
○ Server Implementation is hidden
Stateless 
● Session Cookies 
● Dependent Request
Cacheable 
● HTTP Headers 
● Explicitly 
● Scale 
● Performance
Layered system 
● Load Balancers 
● Reverse Cache Servers
Uniform interface 
● Identification of resources 
○ independent of presentation 
● Manipulation of resources through these 
representations 
○ All data required to modify are present in single request 
● Self-descriptive messages 
○ response is self descriptive via response headers 
● Hypermedia as the engine of application state
Hypermedia as the engine of application 
state 
● Minimum predefined actions 
● Use hyperlinks for additional actions 
● Logic as hyperlink 
○ feature actions discovered from response
Book API 
GET /books Get list of all books 
GET /books/:book_id Get information of a book 
POST /books Create a new book 
PUT /books/1 Modify a book 
DELETE /books/1 Remove a book
Language 
● Different Resource Path 
○ /api/v1/en/books/1 
● Query String 
○ /api/v1/books/1?lang=en 
● Accept-Language 
○ Accept-Language: ar
Content Type 
● Request headers 
○ Accept: application/json 
● resource path 
○ /api/v1/books.json 
● Response headers 
● Headers 
○ Content-Type: application/json; charset=utf-8
Cache 
● Cache-Control 
● Last-Modified 
● Expires 
● Pragma 
● ETag 
● Vary 
○ user-agent, accept-language, Accept
Paging 
● Via Header 
○ 206 Partial Content 
○ Content-Range: 0-9/42 
○ Range: 10-19 
● Query Parameter 
○ ?offset=10&limit=20 
● Providing next page hyperlink in response.
User Agent 
● Device information 
● Application Version 
● BookStore/12.4 (iOS/7.1; iPhone)
Authentication 
● Session as Resource 
● Login POST /session 
● Logout DELETE /session 
● Exchange user/pass for access_token & 
refresh_token 
● Refresh access_token each 24 hours
Authorization 
● Authorization header 
● Cookies
API Versioning 
● Avoid as much as possible 
● Change URLs 
○ /api/v1 
● Via Header 
○ Accept: application/vnd.github.v3+json
Filtering 
● Query Parameters 
○ ?published=true
Sorting 
● Via Query Parameter 
● sort ascending and descending 
● ?sort=+name,-author
Common Mistakes
Common Mistakes 
● Designing the API in isolated world 
○ Do real world while you develop and design 
● Too much data 
○ Only provide what is requested 
● Too much logic in client 
○ Use Hyperlinks more 
● Stateful 
○
DigitalOcean API V1 
GET https://api.digitalocean.com/v1/droplets/new?client_id=[client_id]&api_key=[api_key]&name= 
[droplet_name]&size_id=[size_id]&image_id=[image_id]&region_id=[region_id]&ssh_key_ids=[ssh_key_id1], 
[ssh_key_id2] 
Using Wrong Verb to create and Modify resources
Flickr API 
https://api.flickr.com/services/rest/?method=flickr.photos. 
people.getList 
Ignoring HTTP Verb 
Wrong status code 
Bad naming convention
Best Practices 
● Keep it simple 
○ Do one thing per api request 
● Error messages 
● Documentation with an easy tool to test 
● Naming convention 
● Nested resources 
● Implementation independent
Good Examples 
● Amazon Web Service 
● GitHub Api 
● Twilio
More Resources 
● Using NSURLSession : https://developer.apple. 
com/library/ios/documentation/Cocoa/Conceptual/URLLoadingSystem/Articles/UsingNSURLSession.html 
● Java HTTP Request: http://developer.android.com/reference/org/apache/http/HttpRequest.html 
● API Testig tool http://www.getpostman.com/
Summary
Design Web Service API by HungerStation
Use the right HTTP Verb
Request Headers 
● Accept 
● Accept-Language 
● User-Agent 
● Authorization 
● Content-Type
HTTP Status Code 
● Success 
● Client Error 
● Server Error
Resource Identifier 
● Plural name 
● Minimum predefined actions
Response Headers 
● Content-Type 
● Content-Language
More 
● Clear Error Messages 
● Documentation

More Related Content

What's hot (20)

PPTX
React + Redux + TypeScript === ♥
Remo Jansen
 
PPTX
Odoo Web Services
Celine George
 
PPTX
JavaScript: Implementations And Applications
Pragya Pai
 
PDF
HTML/CSS Crash Course (april 4 2017)
Daniel Friedman
 
PDF
Context API in React
Lucas Lira Gomes
 
PPTX
Angular interview questions
Goa App
 
PDF
Developing Apps With React Native
Alvaro Viebrantz
 
PPTX
Vue Vuex 101
LocNguyen362
 
PPTX
How to Create and Manage Wizard in Odoo 17
Celine George
 
PDF
A Basic Django Introduction
Ganga Ram
 
PPTX
Web development presentation.pptx
ManjeetAgarwal
 
PDF
Flutter state management from zero to hero
Ahmed Abu Eldahab
 
PPTX
React Class Components vs Functional Components: Which is Better?
Fibonalabs
 
PPT
Introduction To Django
Jay Graves
 
PPTX
Entity framework code first
Confiz
 
PDF
Node JS Crash Course
Haim Michael
 
PDF
Redux Toolkit - Quick Intro - 2022
Fabio Biondi
 
PPT
Data controls ppt
Iblesoft
 
PPTX
Angular Lazy Loading and Resolve (Route Resolver)
Squash Apps Pvt Ltd
 
PPTX
Streams In C# Tutorial
Simplilearn
 
React + Redux + TypeScript === ♥
Remo Jansen
 
Odoo Web Services
Celine George
 
JavaScript: Implementations And Applications
Pragya Pai
 
HTML/CSS Crash Course (april 4 2017)
Daniel Friedman
 
Context API in React
Lucas Lira Gomes
 
Angular interview questions
Goa App
 
Developing Apps With React Native
Alvaro Viebrantz
 
Vue Vuex 101
LocNguyen362
 
How to Create and Manage Wizard in Odoo 17
Celine George
 
A Basic Django Introduction
Ganga Ram
 
Web development presentation.pptx
ManjeetAgarwal
 
Flutter state management from zero to hero
Ahmed Abu Eldahab
 
React Class Components vs Functional Components: Which is Better?
Fibonalabs
 
Introduction To Django
Jay Graves
 
Entity framework code first
Confiz
 
Node JS Crash Course
Haim Michael
 
Redux Toolkit - Quick Intro - 2022
Fabio Biondi
 
Data controls ppt
Iblesoft
 
Angular Lazy Loading and Resolve (Route Resolver)
Squash Apps Pvt Ltd
 
Streams In C# Tutorial
Simplilearn
 

Viewers also liked (8)

PPT
Topic6 Basic Web Services Technology
sanjoysanyal
 
PDF
Web service introduction
Sagara Gunathunga
 
PPTX
Web services - A Practical Approach
Madhaiyan Muthu
 
PPTX
Web Services - A brief overview
Raveendra Bhat
 
PDF
Basic Introduction About API Web Service
Hiraq Citra M
 
PDF
Web Services Tutorial
Lorna Mitchell
 
PDF
Web Services (SOAP, WSDL, UDDI)
Peter R. Egli
 
PPT
Web Service Presentation
guest0df6b0
 
Topic6 Basic Web Services Technology
sanjoysanyal
 
Web service introduction
Sagara Gunathunga
 
Web services - A Practical Approach
Madhaiyan Muthu
 
Web Services - A brief overview
Raveendra Bhat
 
Basic Introduction About API Web Service
Hiraq Citra M
 
Web Services Tutorial
Lorna Mitchell
 
Web Services (SOAP, WSDL, UDDI)
Peter R. Egli
 
Web Service Presentation
guest0df6b0
 
Ad

Similar to Design Web Service API by HungerStation (20)

PDF
Don't screw it up! How to build durable API
Alessandro Cinelli (cirpo)
 
PDF
The never-ending REST API design debate
Restlet
 
PDF
Using an API
Adam Culp
 
PPTX
Rest APIs Training
Shekhar Kumar
 
PDF
So you think you know REST - DPC11
Evert Pot
 
PDF
Web Services PHP Tutorial
Lorna Mitchell
 
PDF
Designing RESTful APIs
anandology
 
PDF
Web services tutorial
Lorna Mitchell
 
PDF
The never-ending REST API design debate -- Devoxx France 2016
Restlet
 
PDF
Best Practice in Web Service Design
Lorna Mitchell
 
PDF
What is REST?
Saeid Zebardast
 
PDF
Principles of building effective REST API
Georgy Podsvetov
 
PPTX
Web technologies: HTTP
Piero Fraternali
 
PPTX
rest-api-basics.pptx
AgungSutikno1
 
PDF
Создание API, которое полюбят разработчики. Глубокое погружение
SQALab
 
KEY
Designing a RESTful web service
Filip Blondeel
 
PDF
Introduction to REST - REST Basics - JSON
Matrix823409
 
PDF
Facebook & Twitter API
Fabrice Delhoste
 
ODP
NEPHP '13: Pragmatic API Development
Andrew Curioso
 
PDF
REST APIS web development for backend familiarity
ARTUROGOMEZGARCIA2
 
Don't screw it up! How to build durable API
Alessandro Cinelli (cirpo)
 
The never-ending REST API design debate
Restlet
 
Using an API
Adam Culp
 
Rest APIs Training
Shekhar Kumar
 
So you think you know REST - DPC11
Evert Pot
 
Web Services PHP Tutorial
Lorna Mitchell
 
Designing RESTful APIs
anandology
 
Web services tutorial
Lorna Mitchell
 
The never-ending REST API design debate -- Devoxx France 2016
Restlet
 
Best Practice in Web Service Design
Lorna Mitchell
 
What is REST?
Saeid Zebardast
 
Principles of building effective REST API
Georgy Podsvetov
 
Web technologies: HTTP
Piero Fraternali
 
rest-api-basics.pptx
AgungSutikno1
 
Создание API, которое полюбят разработчики. Глубокое погружение
SQALab
 
Designing a RESTful web service
Filip Blondeel
 
Introduction to REST - REST Basics - JSON
Matrix823409
 
Facebook & Twitter API
Fabrice Delhoste
 
NEPHP '13: Pragmatic API Development
Andrew Curioso
 
REST APIS web development for backend familiarity
ARTUROGOMEZGARCIA2
 
Ad

More from ArabNet ME (20)

PDF
ArabNet Beirut - Keynote: Open Banking - To be or not to be? by Open Bank Pr...
ArabNet ME
 
PDF
Tackling Cyber Threats in Banking Digitization by KRYPTON Security - ArabNet ...
ArabNet ME
 
PDF
Keynote: Open Banking - To be or not to be? by Open Bank Project by ArabNet B...
ArabNet ME
 
PPTX
Keynote: Cyber Security in Banking by CyberQ at ArabNet Riyadh 2018
ArabNet ME
 
PDF
Keynote financial services in 2030 by Michelle Kactis- ArabNet Riyadh 2018
ArabNet ME
 
PDF
The Triangle to Media Success: How to Leverage your Edit, Ads and Audience to...
ArabNet ME
 
PDF
GDPR – Data vs Creative by Nexd
ArabNet ME
 
PDF
Keynote: Why Open Banking/AI/AR is exciting is going to shape Payments and Fi...
ArabNet ME
 
PPTX
Keynote: Raising the Bar on the Ethical Use of Data in Government at the Arab...
ArabNet ME
 
PDF
Research: Smart Cities – What’s in it for the citizen? by McKinsey & Company ...
ArabNet ME
 
PDF
what3words: The future of autonomy and voice control at ArabNet Digital Summi...
ArabNet ME
 
PPTX
Keynote: The State of the European Tech Industry at ArabNet Digital Summit 2018
ArabNet ME
 
PPTX
Keynote: Alternative Funding: IPO vs ICO at ArabNet Digital Summit 2018
ArabNet ME
 
PDF
Keynote: 10 Lessons Every Entrepreneur Must Learn by ConsenSys at ArabNet Bei...
ArabNet ME
 
PDF
Cryptocurrencies a Banking Perspective by Wardrobe Place Capital Management a...
ArabNet ME
 
PDF
Blockchain: Understanding the blockchain and its impact on financial services...
ArabNet ME
 
PDF
Transformation Through Transportation by Hyperloop One at ArabNet Riyadh 2017
ArabNet ME
 
PPTX
Unlock Your Marketing Potential with the Power of AI by IBM at ArabNet Riyadh...
ArabNet ME
 
PDF
E-commerce in a nutshell by ZID at ArabNet Riyadh 2017
ArabNet ME
 
PPTX
Blockchain: Transforming Industries by Fintricity at ArabNet Riyadh 2017
ArabNet ME
 
ArabNet Beirut - Keynote: Open Banking - To be or not to be? by Open Bank Pr...
ArabNet ME
 
Tackling Cyber Threats in Banking Digitization by KRYPTON Security - ArabNet ...
ArabNet ME
 
Keynote: Open Banking - To be or not to be? by Open Bank Project by ArabNet B...
ArabNet ME
 
Keynote: Cyber Security in Banking by CyberQ at ArabNet Riyadh 2018
ArabNet ME
 
Keynote financial services in 2030 by Michelle Kactis- ArabNet Riyadh 2018
ArabNet ME
 
The Triangle to Media Success: How to Leverage your Edit, Ads and Audience to...
ArabNet ME
 
GDPR – Data vs Creative by Nexd
ArabNet ME
 
Keynote: Why Open Banking/AI/AR is exciting is going to shape Payments and Fi...
ArabNet ME
 
Keynote: Raising the Bar on the Ethical Use of Data in Government at the Arab...
ArabNet ME
 
Research: Smart Cities – What’s in it for the citizen? by McKinsey & Company ...
ArabNet ME
 
what3words: The future of autonomy and voice control at ArabNet Digital Summi...
ArabNet ME
 
Keynote: The State of the European Tech Industry at ArabNet Digital Summit 2018
ArabNet ME
 
Keynote: Alternative Funding: IPO vs ICO at ArabNet Digital Summit 2018
ArabNet ME
 
Keynote: 10 Lessons Every Entrepreneur Must Learn by ConsenSys at ArabNet Bei...
ArabNet ME
 
Cryptocurrencies a Banking Perspective by Wardrobe Place Capital Management a...
ArabNet ME
 
Blockchain: Understanding the blockchain and its impact on financial services...
ArabNet ME
 
Transformation Through Transportation by Hyperloop One at ArabNet Riyadh 2017
ArabNet ME
 
Unlock Your Marketing Potential with the Power of AI by IBM at ArabNet Riyadh...
ArabNet ME
 
E-commerce in a nutshell by ZID at ArabNet Riyadh 2017
ArabNet ME
 
Blockchain: Transforming Industries by Fintricity at ArabNet Riyadh 2017
ArabNet ME
 

Recently uploaded (20)

PDF
SS27 Men's Fashion Trend Book Peclers Paris
Peclers Paris
 
PPTX
Light weight Concrete-CONCRETE TECHNOLOGY.
mayurbhandari2123
 
DOCX
CERT HERNANDEZ CHURCH PHILIPPIBNES .docx
michael patino
 
PDF
tdtr.pdfjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj
JuanCParedes
 
PPTX
hall ppt 1 it for basic tamolet .pptx
ashishbehera64
 
PPTX
CompanyReviewTypeOfPowerpointThatIsColor
plukleomarigpuara
 
PPTX
Bldg Mtc 8 Maintance documentation and audits - 25 (2).pptx
MwanamomoMpamba
 
PPTX
High-Rise Interior Mastery by Top 3D Visualization Experts
Yantram Animation Studio Corporation
 
PPTX
sCREW cONVEYOR AUGER DAF SLUDGE SYSTEM TO
viksurs
 
PPTX
Chapter 2-3.pptxnsnsnsnsnsjsjsjsjejeusuejsjsj
hibaaqabdirisaaq331
 
PDF
AI Intervention in Design & Content Creation
YellowSlice1
 
DOCX
Ai vehicle traffic signal detector research proposal.docx
DavidNameza
 
PDF
The Role of Logos as Identity Shapers (IFIC Logo)
Md. Mehedi Hasan Asif
 
PPTX
(2) Cell Wall Inhibitors_Cephalosporins others.pptx
mkurdi133
 
PDF
cs603 ppts .pdf 222222222222222222222222
RabiaNazneen1
 
PPTX
一比一原版(HM毕业证书)慕尼黑应用技术大学毕业证如何办理
Taqyea
 
PPTX
the very teaching plan extra ordinary.pptx
PamelaOdibeli1
 
DOCX
Redefining Master Plans for creating sustainable cities-Jharkhand Conference...
JIT KUMAR GUPTA
 
PPTX
Dndnnnssjsjjsjsjjsssjsjsjjsjsjsjsjjsjsjdn.pptx
Nandy31
 
PDF
🔴BUKTI KEMENANGAN HARI INI SELASA 08 JULI 2025 !!!🔴
GRAB
 
SS27 Men's Fashion Trend Book Peclers Paris
Peclers Paris
 
Light weight Concrete-CONCRETE TECHNOLOGY.
mayurbhandari2123
 
CERT HERNANDEZ CHURCH PHILIPPIBNES .docx
michael patino
 
tdtr.pdfjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj
JuanCParedes
 
hall ppt 1 it for basic tamolet .pptx
ashishbehera64
 
CompanyReviewTypeOfPowerpointThatIsColor
plukleomarigpuara
 
Bldg Mtc 8 Maintance documentation and audits - 25 (2).pptx
MwanamomoMpamba
 
High-Rise Interior Mastery by Top 3D Visualization Experts
Yantram Animation Studio Corporation
 
sCREW cONVEYOR AUGER DAF SLUDGE SYSTEM TO
viksurs
 
Chapter 2-3.pptxnsnsnsnsnsjsjsjsjejeusuejsjsj
hibaaqabdirisaaq331
 
AI Intervention in Design & Content Creation
YellowSlice1
 
Ai vehicle traffic signal detector research proposal.docx
DavidNameza
 
The Role of Logos as Identity Shapers (IFIC Logo)
Md. Mehedi Hasan Asif
 
(2) Cell Wall Inhibitors_Cephalosporins others.pptx
mkurdi133
 
cs603 ppts .pdf 222222222222222222222222
RabiaNazneen1
 
一比一原版(HM毕业证书)慕尼黑应用技术大学毕业证如何办理
Taqyea
 
the very teaching plan extra ordinary.pptx
PamelaOdibeli1
 
Redefining Master Plans for creating sustainable cities-Jharkhand Conference...
JIT KUMAR GUPTA
 
Dndnnnssjsjjsjsjjsssjsjsjjsjsjsjsjjsjsjdn.pptx
Nandy31
 
🔴BUKTI KEMENANGAN HARI INI SELASA 08 JULI 2025 !!!🔴
GRAB
 

Design Web Service API by HungerStation

  • 1. Design Web Service API Arabnet 2014 Riyadh
  • 5. What ● CORBA ● Ice ● SOAP ● REST
  • 6. Debates ● Binary over TCP: Performance ○ APN ● Text over HTTP: Flexibility ● Verbose ● Strict
  • 7. Programmer Interface They’ll judge you by your API
  • 8. Why Let other programmers build on top of your service
  • 9. Why ● Mobile applications ● Exposure ● Integration with third party services ● Technical ○ Abstraction ○ Simplicity ● Everyone else has API!
  • 10. How
  • 11. SOAP Simple Object Access protocol
  • 14. HTTP
  • 17. HTTP Request GET /books HTTP/1.1 User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT) Host: www.example.com Accept-Language: en-us Accept-Encoding: gzip, deflate Connection: Keep-Alive
  • 18. HTTP Request Method GET /books HTTP/1.1 User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT) Host: www.example.com Accept-Language: en-us Accept-Encoding: gzip, deflate Connection: Keep-Alive
  • 19. HTTP Request Resource GET /books HTTP/1.1 User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT) Host: www.example.com Accept-Language: en-us Accept-Encoding: gzip, deflate Connection: Keep-Alive
  • 20. HTTP Request Headers GET /books HTTP/1.1 User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT) Host: www.example.com Accept-Language: en-us Accept-Encoding: gzip, deflate Connection: Keep-Alive
  • 21. HTTP Request Payload POST /books HTTP/1.1 User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT) Host: www.example.com Content-Type: application/x-www-form-urlencoded Content-Length: length Accept-Language: en-us Accept-Encoding: gzip, deflate Connection: Keep-Alive name=The+Hitchhiker% 27s+Guide+to+the+Galaxy&author=Douglas+Adams
  • 22. HTTP Verb ● GET ● POST ● PUT/PATCH ● DELETE
  • 23. Resource ● Model ● Date element ● URL ● /books ● /books/1
  • 24. Request Headers ● explain the request ● predefined headers ○ Accept-Language, Accept, Content-Encoding, User- Agent, Referer, Authorization, ... ● Custom headers ○ X-Pjax-C, X-Proto, X-Forwarded-For
  • 25. Request Payload ● Data ● Content-Type ● File
  • 27. GET /books/1 HTTP/1.1 User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT) Host: www.example.com Accept-Language: en-us Accept-Encoding: gzip, deflate Connection: Keep-Alive select * from books where id=1;
  • 28. POST Create a new model
  • 29. POST /books HTTP/1.1 User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT) Host: www.example.com Content-Type: application/x-www-form-urlencoded Content-Length: length Accept-Language: en-us Accept-Encoding: gzip, deflate Connection: Keep-Alive name=The+Hitchhiker%27s+Guide+to+the+Galaxy&author=Douglas+Adams insert into books (name, author) values (‘The Hitchhiker's Guide to the Galaxy’,’ Douglas Adams’);
  • 31. PATCH /books/1 HTTP/1.1 User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT) Host: www.example.com Content-Type: application/x-www-form-urlencoded Content-Length: length Accept-Language: en-us Accept-Encoding: gzip, deflate Connection: Keep-Alive published=true update books set published=true;
  • 32. DELETE Remove a resource
  • 33. DELETE /books/1 HTTP/1.1 User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT) Host: www.example.com Accept-Language: en-us Accept-Encoding: gzip, deflate Connection: Keep-Alive delete from books where id=1;
  • 35. Objective C (iOS) //create a reusable session NSURLSessionConfiguration* sessionConfiguration; NSURLSession *session; sessionConfiguration=[NSURLSessionConfiguration defaultSessionConfiguration]; [sessionConfiguration setHTTPAdditionalHeaders: @{@"Accept":@"application/json"}]; session=[NSURLSession sessionWithConfiguration:sessionConfiguration]; //execute the request NSURL* url=[NSURL URLWithString:@"https://secure-escarpment-9317.herokuapp.com/books.json"]; NSURLSessionDataTask* task=[session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { ا// handling response }]; [task resume];
  • 36. HTTP Response HTTP/1.1 200 OK Content-Type:application/json; charset=utf-8 Date:Mon, 10 Nov 2014 06:42:57 GMT Server:nginx/1.6.2 Content-Length: 72 Connection: keep-alive {"name": "The Hitchhiker's Guide to the Galaxy",author: "Douglas Adams"}
  • 37. Status HTTP/1.1 200 OK Content-Type:application/json; charset=utf-8 Date:Mon, 10 Nov 2014 06:42:57 GMT Server:nginx/1.6.2 Content-Length: 72 Connection: keep-alive {"name": "The Hitchhiker's Guide to the Galaxy",author: "Douglas Adams"}
  • 38. Headers HTTP/1.1 200 OK Content-Type:application/json; charset=utf-8 Date:Mon, 10 Nov 2014 06:42:57 GMT Server:nginx/1.6.2 Content-Length: 72 Connection: keep-alive {"name": "The Hitchhiker's Guide to the Galaxy",author: "Douglas Adams"}
  • 39. Content HTTP/1.1 200 OK Content-Type:application/json; charset=utf-8 Date:Mon, 10 Nov 2014 06:42:57 GMT Server:nginx/1.6.2 Content-Length: 79 Connection: keep-alive {"name": "The Hitchhiker's Guide to the Galaxy",author: "Douglas Adams",”id”:1}
  • 40. Status Codes 2XX OK 3XX Redirection 4XX Client Error 5XX Server Error
  • 41. 2XX Successful Codes 200 Successful 201 Created 202 Accepted 204 No Content 206 Partial Content
  • 42. 3XX Redirect Codes 301 Permanently 301 Temporary
  • 43. 4XX Client Error Codes 400 Bad Request 401 Unauthorized 403 Forbidden 404 No Found 422 Unprocessable entity
  • 44. 5XX Server Error Codes 500 Internal Server Error 501 Service Unavailable
  • 45. HTTP Response Headers ● Explain response ● Required headers ● Standard headers ● Custom headers
  • 46. HTTP Response Content { "id": 3, "title": "The Hitchhiker's Guide to the Galaxy", "author": "Douglas Adams", "published": false, "created_at": "2014-11-10T13:39:24.894Z", "updated_at": "2014-11-10T13:39:24.894Z" }
  • 47. Create Response Example # POST /books # POST /books.json def create @book = Book.new(book_params) respond_to do |format| if @book.save format.html { redirect_to @book, notice: 'Book was successfully created.' } format.json { render :show, status: :created, location: @book } else format.html { render :new } format.json { render json: @book.errors, status: :unprocessable_entity } end end end
  • 48. Create Response Example public function create() { $book = new Book; $book->title = Request::get('title'); $book->author = Request::get('author'); $book->save(); return Response::json(array( 'error' => false, 'urls' => $urls->toArray()), 201 ); }
  • 49. REST
  • 50. Client–server ● Separation of concerns ○ Server Implementation is hidden
  • 51. Stateless ● Session Cookies ● Dependent Request
  • 52. Cacheable ● HTTP Headers ● Explicitly ● Scale ● Performance
  • 53. Layered system ● Load Balancers ● Reverse Cache Servers
  • 54. Uniform interface ● Identification of resources ○ independent of presentation ● Manipulation of resources through these representations ○ All data required to modify are present in single request ● Self-descriptive messages ○ response is self descriptive via response headers ● Hypermedia as the engine of application state
  • 55. Hypermedia as the engine of application state ● Minimum predefined actions ● Use hyperlinks for additional actions ● Logic as hyperlink ○ feature actions discovered from response
  • 56. Book API GET /books Get list of all books GET /books/:book_id Get information of a book POST /books Create a new book PUT /books/1 Modify a book DELETE /books/1 Remove a book
  • 57. Language ● Different Resource Path ○ /api/v1/en/books/1 ● Query String ○ /api/v1/books/1?lang=en ● Accept-Language ○ Accept-Language: ar
  • 58. Content Type ● Request headers ○ Accept: application/json ● resource path ○ /api/v1/books.json ● Response headers ● Headers ○ Content-Type: application/json; charset=utf-8
  • 59. Cache ● Cache-Control ● Last-Modified ● Expires ● Pragma ● ETag ● Vary ○ user-agent, accept-language, Accept
  • 60. Paging ● Via Header ○ 206 Partial Content ○ Content-Range: 0-9/42 ○ Range: 10-19 ● Query Parameter ○ ?offset=10&limit=20 ● Providing next page hyperlink in response.
  • 61. User Agent ● Device information ● Application Version ● BookStore/12.4 (iOS/7.1; iPhone)
  • 62. Authentication ● Session as Resource ● Login POST /session ● Logout DELETE /session ● Exchange user/pass for access_token & refresh_token ● Refresh access_token each 24 hours
  • 63. Authorization ● Authorization header ● Cookies
  • 64. API Versioning ● Avoid as much as possible ● Change URLs ○ /api/v1 ● Via Header ○ Accept: application/vnd.github.v3+json
  • 65. Filtering ● Query Parameters ○ ?published=true
  • 66. Sorting ● Via Query Parameter ● sort ascending and descending ● ?sort=+name,-author
  • 68. Common Mistakes ● Designing the API in isolated world ○ Do real world while you develop and design ● Too much data ○ Only provide what is requested ● Too much logic in client ○ Use Hyperlinks more ● Stateful ○
  • 69. DigitalOcean API V1 GET https://api.digitalocean.com/v1/droplets/new?client_id=[client_id]&api_key=[api_key]&name= [droplet_name]&size_id=[size_id]&image_id=[image_id]&region_id=[region_id]&ssh_key_ids=[ssh_key_id1], [ssh_key_id2] Using Wrong Verb to create and Modify resources
  • 71. Best Practices ● Keep it simple ○ Do one thing per api request ● Error messages ● Documentation with an easy tool to test ● Naming convention ● Nested resources ● Implementation independent
  • 72. Good Examples ● Amazon Web Service ● GitHub Api ● Twilio
  • 73. More Resources ● Using NSURLSession : https://developer.apple. com/library/ios/documentation/Cocoa/Conceptual/URLLoadingSystem/Articles/UsingNSURLSession.html ● Java HTTP Request: http://developer.android.com/reference/org/apache/http/HttpRequest.html ● API Testig tool http://www.getpostman.com/
  • 76. Use the right HTTP Verb
  • 77. Request Headers ● Accept ● Accept-Language ● User-Agent ● Authorization ● Content-Type
  • 78. HTTP Status Code ● Success ● Client Error ● Server Error
  • 79. Resource Identifier ● Plural name ● Minimum predefined actions
  • 80. Response Headers ● Content-Type ● Content-Language
  • 81. More ● Clear Error Messages ● Documentation