REST APIs

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

REST API

Any API that uses Representational State Transfer (REST), which means that the two programs, on separate computers, use HTTP messages to request and transfer data. -machine-readable • JavaScript runs in browser • JavaScript (client-side) receives JSON data from server • JavaScript renders data on page • Interoperability between different web systems • REST is not ... -• A standard -• A language • REST is ... -• A collection of principles -• Some best practices -• Usually uses HTTP and JSON

User-Agent

Any application, such as a Web browser, mobile phone, smartphone or help engine, that renders HTML for display to users. (so basically which browser is making the request)

POST request

-Sends data to server like from a web form -create a new datum/object ex. create a new post -Request includes JSON body POST localhost:8000/api/v1/p/ HTTP/1.0 { "img_url": "122a7d27ca1d7420a1072f695d9290fad4501a41.jpg", "owner": "awdeorio", ... }

Uniform Interface

-• Resource-based -• Manipulation of resources through representations -• Self-descriptive messages -• Hypermedia as the engine of application state (HATEOAS)

Valid JSON

Check by: $ curl -s https://api.github.com/users/awdeorio | jsonlint Pitfall: no trailing commas allowed! { "login":"awdeorio", "id":7503005, ... "updated_at": "2017-12-12T19:11:17Z" /, }

HTTP content type

Content type describes the "file" type and encoding File types: HTML, JSON Ex. Content-Type: text/html; charset=UTF-8

HTTP request Methods

GET, HEAD, POST, OPTIONS, PUT, DELETE, TRACE, CONNECT, PATCH -Request method indicates server action

HTTP response headers

Headers that accompany the response (again most are optional)

Pagination

How a document is divided into pages. REST API enables this • List views should return a limited number of items -• What if there were 10 million posts? • Sensible default, e.g., 10 posts -• $ curl localhost:8000/api/v1/p/ - Get the next 10 results -• $ curl localhost:8000/api/v1/p/?page=1 • Customizable size -• $ curl localhost:8000/api/v1/p/?size=20

Why does idempotency matter?

If a request fails, can we automatically try again? Only if it is idempotent. • Idempotent methods are distinguished because the request can be repeated automatically if a communication failure occurs before the client is able to read the server's response. For example, if a client sends a PUT request and the underlying connection is closed before any response is received, then the client can establish a new connection and retry the idempotent request. It knows that repeating the request will have the same intended effect, even if the original request succeeded, though the response might differ.

Httpie

Makes it look pretty and colorful -improved CLI and color coding $ http https://api.github.com/users/awdeorio HTTP/1.0 200 OK { "login":"awdeorio", "id":7503005, ...

JSON structures

Object: a collection of pairs/value pairs -other languages call it a hash table (c++), dictionary (python), etc -ex. { "name": "DeOrio", "num_chicken": 4 } Array: an ordered list of values -other languages call it a arrat, vector, list, etc -ex. [ "Marilyn", "Maude", "Myrtle II", "Mabel"] A value is: string, number, true, false, null, Object, Array

curl

REST API at the command line HTTP GET request returns a JSON-formatted string $ curl https://api.github.com/users/awdeorio { "login": "awdeorio", "id": 7503005, ...

List view AKA collection view

REST APIs often expose collections of items $ curl localhost:8000/api/v1/p/ { "results": [ { "postid": 3, "url": "/api/v1/p/3/" }, { "postid": 2, "url": "/api/v1/p/2/" }, ... ] }

HTTP status code

Response starts with a status code • 1XX: Informational • 2XX: Successful • 3XX: Client Error • 4XX: Server Error

DELETE request

delete datum/object • Request URL includes an ID • No body in request DELETE localhost:8000/api/v1/p/1/ HTTP/1.0

HOST

distinguishes between DNS names sharing a single IP address • Required as of HTTP/1.1

Stateless

everything needed to make the request is in the request itself - URI, query-string parameters, body, or headers After the server does it's processing, the appropriate state, or the piece(s) of state that matter, are communicated back to the client via headers, status and response body POST /api/v1/p/ HTTP/1.0 HTTP/1.0 201 Created { // contents of created object }

HTTP request headers

headers accompany request but most of them are optional ex. of headers: -host -user-agent -accept ex. $ curl --verbose http://cse.eecs.umich.edu/ > index.html * Connected to cse.eecs.umich.edu (141.212.113.143) port 80 (#0) > GET / HTTP/1.0 > Host: cse.eecs.umich.edu > User-Agent: curl/7.54.0 > Accept: */*

Detail view / item view

it returns one object from the database

httpbin.org

its an echo server so basically just responds with whatever you send it $ http POST httpbin.org/anything hello=world ... { ... "json": { "hello": "world" }, "method": "POST", "url": "http://httpbin.org/anything" }

PUT request

replace the entire datum/object • Request URL includes an ID • Request includes JSON body Ex. replace an entire post The JSON body is long, and contains a replacement value for every field PUT localhost:8000/api/v1/p/1/ HTTP/1.0 { "img_url": ..., "owner": "jflinn", "owner_img_url": ..., ... }

GET request

request a resource return a datum (like loading a page) ex. return a post

HEAD request

same thing as GET but without response body (checks if the page has changed)

slug

the ID part of the URL ex. "url": "/api/v1/p/1/"

PATCH request

update part of a datum / modifies part of an existing object -Request URL includes an ID - Request includes JSON body Ex. changing pic in post - JSON body is short and only include the field that is going to be changed PATCH localhost:8000/api/v1/p/1/ HTTP/1.0 { "img_url": "ad7790405c539894d25ab8dcf0b79eed3341e109.jpg", }

accept

which content ("file") types the client will accept

REST API status codes

• 200 OK • 201 Created -• Successful creation after POST • 204 No Content -• Successful DELETE • 304 Not Modified -• Used for conditional GET calls to reduce band-width usage • 400 Bad Request -• General error • 401 Unauthorized -• Missing or invalid authentication • 403 Forbidden -• User is not authorized • 404 Not Found -• Resource could not be found • 409 Conflict -• E.g., duplicate entries and deleting root objects when cascade-delete is not supported • 500 Internal Server Error -• General catch-all for server-side exceptions

Summary

• A client and a server can communicate via a REST API • Two servers can communicate via a REST API • REST APIs use HTTP • REST APIs are machine-readable • REST APIs usually return JSON data

Layered

• A client cannot ordinarily tell whether it is connected directly to the end server, or to an intermediary along the way • No need to connect to a specific machine • Just need the data from this URI

Cacheable

• Clients cache some kinds of responses to eliminate requests • Example: cache an image so you don't load it every time • Responses must implicitly or explicitly define themselves as cacheable • Example: Last-Modified header

DELETE response

• DELETE returns 204 NO CONTENT on success • No body in response DELETE localhost:8000/api/v1/p/1/ HTTP/1.0 ... HTTP/1.0 204 NO CONTENT

Uniform interface: self-descriptive messages

• Each message includes enough information to describe how to process the message • Content-Type and charset GET /api/v1/p/1/ HTTP/1.0 HTTP/1.0 200 OK > Content-Type:application/json; charset=utf-8 ... { ... }

Not Found

• GET a deleted item, receive a 404 response DELETE localhost:8000/api/v1/p/1/ HTTP/1.0 HTTP/1.0 204 NO CONTENT GET localhost:8000/api/v1/p/1/ HTTP/1.0 HTTP/1.0 404 NOT FOUND

Uniform interface: HATEOAS

• HATEOAS: Hypermedia as the Engine of Application State • Clients deliver state via body contents, query-string parameters, request headers and the requested URI (the resource name). • Services deliver state to clients via body content, response codes, and response headers. This is technically referred-to as hypermedia (or hyperlinks within hypertext). • Everything you need is in the request POST /api/v1/p/ HTTP/1.0 { "img_url": "122a7d27ca1d7420a1072f695d9290fad4501a41.jpg", "owner": "awdeorio", ... } • Links are contained in the returned body (or headers) to supply the URI for retrieval of the object itself or related objects. GET /api/v1/p/1/ HTTP/1.0 HTTP/1.0 200 OK { ..., "url": "/api/v1/p/1/" }

REST APIs use HTTP

• HTTP request includes a method • HTTP response includes a status code and JSON data

Uniform Interface: resource-based

• Individual resources are identified in requests using URIs as resource identifiers. • Think of a URI like a pointer • ID in the URL GET /api/v1/p/1/ HTTP/1.0 ^

JSON

• JSON: JavaScript Object Notation • Lightweight data-interchange format -• Based on JavaScript syntax • Uses conventions familiar to programmers in many languages • Commonly used to send data from a server to a web client -• Client parses JSON using JavaScript and displays content • Ubiquitous with REST APIs

Idempotent

• Multiple identical requests should have the same effect on the server as a single request • The same request can be made twice with no negative consequences on the server • Does not mean that the same request always returns the same response • Does mean that a request has NO side effects NOT idempotent: POST idempotent: DELETE, PUT, PATCH

PATCH response

• PATCH returns 200 OK on success • Response includes a copy of the entire modified object PATCH localhost:8000/api/v1/p/1/ HTTP/1.0 ... HTTP/1.0 200 OK { "img_url": "ad7790405c539894d25ab8dcf0b79eed3341e109.jpg", "owner": "awdeorio", ... "url": "/api/v1/p/1/" }

POST response

• POST returns 201 CREATED on success • Response includes a copy of the created object • Object usually includes a link to itself POST localhost:8000/api/v1/p/ HTTP/1.0 ... HTTP/1.0 201 CREATED { "img_url": "122a7d27ca1d7420a1072f695d9290fad4501a41.jpg", "owner": "awdeorio", ... "url": "/api/v1/p/1/" }

PUT response

• PUT returns 200 OK on success • Response includes a copy of the entire modified object PUT localhost:8000/api/v1/p/1/ HTTP/1.0 ... HTTP/1.0 200 OK { "img_url": ..., "owner": "jflinn", "owner_img_url": ..., ... }

Safe

• Request methods are safe if they are read-only • No state change on the server • GET and HEAD requests are safe

Code on demand (optional)

• Servers are able to temporarily extend or customize the functionality of a client by transferring logic to it that it can execute • Examples of this may include compiled components such as Java applets and client-side scripts such as JavaScript • Not common

Client-server architecture

• The uniform interface separates clients from servers • Abstraction between client and server • Can change the server without modifying the client • Can change the client without modifying the server • Example: database is too slow, replace portions of it with key-value store like Redis

REST design principles

• Uniform interface • Client-server architecture • Stateless • Cacheable • Layered • Code on demand (optional)

Uniform interface: manipulation of resources through representations

• When a client holds a representation of a resource, including any metadata attached, it has enough information to modify or delete the resource on the server. • Object usually contains a link to itself GET /api/v1/p/1/ HTTP/1.0 HTTP/1.0 200 OK { ..., "url": "/api/v1/p/1/" }


Ensembles d'études connexes

Pers Fin Ch 10 Financial Planning

View Set

AP English Language + Composition - MCQ

View Set

Chapter 6 The Human Population and Its Impact | APES

View Set

Assignment 3: Chap 49 (Opioids) & Chap 58 (SUD)

View Set

Chapter 2. FINANCIAL STATEMENTS, TAXES, AND CASH FLOW

View Set

Chapter 6 Energy and Metabolism (SB)

View Set

BUS171 Chapter 3: Managing Systems Projects

View Set