Building Friendly, RESTful Web APIs

 

What is a Web API?

  • a programmatic interface to some system, exposed over the web
  • sometimes referred to as a web service
 

The Internet of Old


 

The New Internets

 

Leveraging heterogeneous clients without a uniformed interface

 

 
REST...

 

What is REST?

  • Representational State Transfer
  • Client -> Server
  • Requests and responses built around the transfer of resource representations
  • Resource -> Noun
  • Representation -> State of Resource (json, xml)
 

Leveraging heterogeneous clients with REST

 

Let's get opinionated

  • You're already using HTTP, so use HTTP
  • Status codes are your friends
  • Use query-strings to modify queries
  • Create aliases for common queries
 

You're already using HTTP, so use HTTP

GET /videos/3/comments - gets a list of all the comments for video #3GET /videos/3/comments/7 - gets comment #7 for video #3POST /videos/3/comments - creates a new comment for video #3PUT /videos/3/comments/7 - updates comment #7 for video #3PATCH /videos/3/comments/7 - partially updates comment #7 for video #3DELETE /videos/3/comments/7 - deletes comment #7 for video #3
 
Relationships - (/◔ ◡ ◔)/
GET /videos - gets a list of videosGET /videos/3 - gets video #3POST /videos - creates a new videoPUT /videos/3 - updates a video #3PATCH /videos/3 - partially updates video #3DELETE /videos/3 - deletes video #3
 

Status codes are your friends

  • HTTP specifies a bunch of useful status codes
  • By properly using these API users can better handle server responses
  • Important status code classes
    • 2xx - Success
    • 4xx - Client Error
    • 5xx - Server Error
 

Use query-strings to modify queries 

  • Filtering
    • /videos?type=music - gets a list of music videos
  • Sorting
    • /videos?sort=-views - gets a list of videos sorted by views descending
  • Field limiting
    • /videos?fields=uploader,title,create_date - gets just the uploader, title, and creation date of all the videos
 

Create aliases for common queries

  • Retrieve the current featured videos
    • /videos/featured
  • Retrieve the most recent videos
    • /videos/recently_uploaded
 

Follow your 

 

Any questions?

 

Building a Friendly, RESTful API

By hkal

Building a Friendly, RESTful API

  • 1,703