ReST Web Services
In questa pagina 7
So far HTTP has carried documents meant for a person (HTML pages; see HTTP and the WebThe application layer is the top of the stack and only uses transport services; the Web is a distributed client-server hypertext service whose pages have URLs of the form protocol://host:port/path; HTTP runs over TCP (server port 80), is stateless and uses text messages (request or status line, headers, blank line, body) with methods GET, POST, HEAD, PUT, DELETE and status codes 2xx to 5xx; a page with N embedded objects needs 2(N+1) RTT with non-persistent connections and N+2 RTT with a persistent connection (transmission times neglected), cookies give HTTP a memory through Set-Cookie and Cookie headers, and a proxy (web cache) keeps copies of recent responses to cut load, traffic and delay.HTTP and the Web →). An application may instead want to call a service on another machine and receive data, not a page: the price of a book, the list of exam dates, the outcome of a payment. This is a web service.
Definition (web service). A software system designed to support machine-to-machine interaction over a network, in which requests and responses are messages in a standard format, usually carried by HTTP.
Three things are needed: a data format (XML or JSON), a way to express operations (SOAP messages, or HTTP methods applied to resources with REST) and a transport (HTTP). This note presents the formats, SOAP and REST and compares them. The server side of such services is an HTTP server written with sockets (Socket ProgrammingA socket is a communication endpoint identified like a file descriptor; a TCP server runs socket, setsockopt, bind, listen, accept, read/write, close, while the client runs socket, connect, read/write, close.Socket Programming →), as in Client-Server ProgrammingIn a network application the program writes the application-layer messages while TCP or UDP, IP and the drivers live in the kernel; the boundary is the socket API, which is the service access point of the transport layer (address = IP address plus port); the client-server model works like a function call (the client asks and waits, the server is always listening) and is contrasted with peer-to-peer and publish-subscribe.Client-Server Programming →.
XML
XML (eXtensible Markup Language, W3C) describes structured data as a tree of elements delimited by markers (tags). Unlike HTML the tags are not predefined: whoever designs the format defines them.
<?xml version="1.0" encoding="UTF-8"?>
<book id="42">
<title>Computer Networks</title>
<authors>
<author>Rossi</author>
<author>Bianchi</author>
</authors>
<price currency="EUR">29.9</price>
<available>true</available>
</book>Rules for a document to be well formed:
- there is one root element;
- every opening tag has its closing tag and elements are correctly nested (
<a><b></b></a>, never<a><b></a></b>); an empty element can be written<br/>; - names are case-sensitive;
- attribute values (
id="42") are in quotes; - special characters in text are written as entities:
<(<),>(>),&(&),",'; for a block of raw text there is<![CDATA[ ... ]]>; - the initial declaration
<?xml version="1.0" encoding="UTF-8"?>is optional but recommended; - comments are
<!-- ... -->.
Namespaces (xmlns:m="http://example.com/library") avoid conflicts between tags of different vocabularies: <m:price> and <p:price> are different elements. Validation (the document conforms to a schema) is done with a DTD or, better, with XML Schema (XSD), which declares elements, types and constraints: a well-formed document is not automatically valid. XML is read in two ways: DOM (everything is loaded into an in-memory tree) or SAX (events while reading, without keeping everything). It is sent with Content-Type: application/xml or text/xml.
JSON
JSON (JavaScript Object Notation, RFC 8259) is a lighter text format, born from the syntax of JavaScript objects and now used by almost all languages. It has six value types:
| type | syntax | example |
|---|---|---|
| object | { "key": value, ... } (string keys) |
{"id": 42} |
| array | [ value, ... ] |
["Rossi", "Bianchi"] |
| string | characters in double quotes, with escapes | "Computer Networks" |
| number | decimal (no leading zeros, no hexadecimal, no NaN) |
29.9, -3, 1e3 |
| boolean | true or false |
true |
| null | null |
null |
Escapes in strings: \", \\, \/, \b, \f, \n, \r, \t, \uXXXX (Unicode character with 4 hexadecimal digits). A control character (code below 0x20) must be escaped. Comments and trailing commas are not allowed. The text is exchanged in UTF-8; the MIME type is application/json.
The same book in JSON:
{"id":42,"title":"Computer Networks","authors":["Rossi","Bianchi"],"price":29.9,"available":true}XML or JSON
In compact form (no spaces or line breaks) the same book takes 97 bytes in JSON against 164 in XML (with the id as an attribute and no currency attribute): the closing tag repeats every name.
| XML | JSON | |
|---|---|---|
| size | larger (opening and closing tags) | smaller |
| data types | text only (types declared with XSD) | numbers, booleans, null, native arrays |
| readability for a program | needs an XML parser, DOM or SAX | matches language structures (objects, lists) |
| structure | elements, attributes, mixed text, namespaces, comments | objects and arrays only |
| validation | DTD, XSD, XSLT to transform | JSON Schema |
| typical use | SOAP, documents, complex configurations | REST APIs, data exchange on the Web |
Neither is better in absolute terms: XML is richer (namespaces, documents with text mixed with markup), JSON is simpler and in practice the standard for Web APIs.
JSON in C
C has neither an "object" type nor a standard JSON library. Libraries (cJSON, jansson, json-c) are used or, for flat objects, a minimal extractor that looks up the key and reads the value, with three precautions: handle escape sequences in strings, check buffer limits, and escape the values when generating output (quotes, backslashes and control characters: a title Say "hi" must become "Say \"hi\"", otherwise the generated JSON is broken). An extractor based on strstr is not a real parser: it does not validate the structure and can mistake a key for an equal string inside a value.
SOAP
SOAP (Simple Object Access Protocol, W3C; version 1.2 of 2003) is a protocol for exchanging XML messages between applications, independent of the transport but almost always used over HTTP. A message is an envelope (Envelope) with an optional Header (surrounding information: authentication, transactions) and a Body (the content: the requested operation or the result).
<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope">
<soap:Body>
<m:GetPrice xmlns:m="http://example.com/library">
<m:id>42</m:id>
</m:GetPrice>
</soap:Body>
</soap:Envelope>With the HTTP binding the envelope travels in the body of a POST to a single address (the endpoint), whatever the operation: the operation is inside the Body, not in the URI or in the method.
POST /services/library HTTP/1.1
Host: example.com
Content-Type: application/soap+xml; charset=utf-8
Content-Length: 259
<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope ...>...GetPrice id 42...</soap:Envelope>(In SOAP 1.1 the type is text/xml and a SOAPAction header indicates the action.) The response is another envelope:
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope">
<soap:Body>
<m:GetPriceResponse xmlns:m="http://example.com/library">
<m:price>29.90</m:price>
</m:GetPriceResponse>
</soap:Body>
</soap:Envelope>Errors are signalled by a Fault element in the Body (with Code, for instance Sender if the client is at fault and Receiver if the server is, Reason, optional Detail); the HTTP binding uses status 500 for service Faults.
The contract of a SOAP service is a WSDL file (Web Services Description Language, XML) describing messages, operations, types (with XSD), the protocol binding and the address: a program reads it and automatically generates the code to call the service. Thanks to WSDL and to the many WS-* standards (security, transactions, reliability) SOAP suits formal enterprise environments, at the cost of verbose messages, heavy XML parsing and high complexity.
REST
REST (REpresentational State Transfer) is an architectural style, described by Roy Fielding in his 2000 doctoral thesis, that directly exploits how the Web is made: not a protocol but a set of constraints. A service that respects them is called RESTful.
The constraints
| constraint | meaning |
|---|---|
| client-server | separation between user interface and data |
| stateless | every request contains all the information needed; the server does not keep the client's context between requests (no server-side session) |
| cache | responses declare whether they can be stored |
| uniform interface | resources identified by URIs; manipulated through representations; self-descriptive messages (method, code, Content-Type); hypertext links (HATEOAS) |
| layered system | between client and server there can be proxies, gateways, caches, load balancers |
| code on demand (optional) | the server can send code executed by the client (JavaScript) |
Resources and representations
The central concept is the resource: anything that has a name (a book, a user, an order, a list), identified by a URI. The client does not see the resource but a representation of it (JSON, XML, HTML) chosen by negotiation (Accept, Content-Type). The operations are the HTTP methods, with their standard meaning:
| operation | method and URI | success | request body | notes |
|---|---|---|---|---|
| list | GET /books |
200 |
no | safe, idempotent |
| read | GET /books/42 |
200 |
no | 404 if it does not exist |
| create | POST /books |
201 Created with Location: /books/43 |
representation of the new resource | the server chooses the identifier; not idempotent |
| replace | PUT /books/42 |
200 or 204 |
complete representation | idempotent |
| partial modification | PATCH /books/42 |
200 |
only the fields to change | |
| delete | DELETE /books/42 |
204 No Content |
no | idempotent (the second one may give 404) |
URIs indicate nouns, not verbs: /books/42 and not /readBook?id=42. Collections are filtered with the query: GET /books?author=Rossi&page=2. Status codes are part of the contract: 200 success, 201 created, 204 success without body, 400 malformed request, 401 authentication required, 403 forbidden, 404 nonexistent resource, 405 method not allowed (with Allow), 409 conflict (the resource already exists, inconsistent version), 415 unsupported content type, 500 server error.
Example. A complete session with a task service:
POST /tasks HTTP/1.1
Host: 127.0.0.1:8080
Content-Type: application/json
Content-Length: 24
{"title":"Buy the milk"}The server answers:
HTTP/1.1 201 Created
Content-Type: application/json
Content-Length: 44
Location: /tasks/1
Connection: close
{"id":1,"title":"Buy the milk","done":false}GET /tasks/9 HTTP/1.1
Host: 127.0.0.1:8080
HTTP/1.1 404 Not Found
Content-Type: application/json
{"error":"no such task"}PUT /tasks/1 HTTP/1.1
Content-Type: application/json
Content-Length: 28
{"title":"Milk","done":true}
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 35
{"id":1,"title":"Milk","done":true}DELETE /tasks/1 HTTP/1.1
HTTP/1.1 204 No ContentObserve: the creation response has 201 and the Location header, the DELETE response has neither body nor Content-Type, and errors have a JSON body with a message.
Other aspects
- Idempotence. Repeated
GET,PUTandDELETEhave the same effect as a single one: a client can retry after a network error.POSTdoes not: a retry can create two resources (idempotency keys are used if needed). - Stateless does not mean without authentication: every request carries its own credentials (
Bearertoken,Authorization), so the server can be replicated behind a load balancer without sharing sessions. - HATEOAS. The response contains links to the possible actions (
"links": {"self": "/books/42", "authors": "/books/42/authors"}): the client follows them instead of building URIs by hand. It is the least applied part of the style. - Maturity levels (Richardson): 0 a single endpoint and
POSTas a tunnel (SOAP); 1 resources with distinct URIs; 2 correct use of HTTP methods and status codes; 3 hypertext links. Most "REST" APIs are at level 2. - Versions. They are indicated in the URI (
/v1/books) or by negotiation; a published API is not changed in an incompatible way.
A REST service as an HTTP server
A REST server is an HTTP server with three extra elements: routing (recognising /tasks and /tasks/ID and the method), reading the body with Content-Length in POST/PUT with a check of Content-Type and size (411, 413, 415), and JSON serialisation with escaping.
REST and SOAP compared
| SOAP | REST | |
|---|---|---|
| nature | protocol with rigid rules | architectural style, flexible |
| format | XML only (envelope) | JSON, XML, HTML, text... |
| transport | HTTP (but also others) | HTTP |
| operations | in the message Body, all with POST to the same URI |
HTTP methods on different URIs |
| description | WSDL | OpenAPI (optional) |
| errors | Fault element (status 500) |
HTTP status codes (404, 400...) |
| cache | difficult (always POST) |
natural for GET |
| performance | large messages, heavy parsing | lightweight |
| typical use | enterprise integrations with WS-* standards |
public APIs, web and mobile applications |
Security and good practice
- Encrypt with HTTPS: data and credentials travel in clear over HTTP.
- Validate every input (types, lengths, ranges): a well-formed JSON can contain absurd values. For XML disable external entities (the XXE attack).
- Limit body size and nesting depth (a document nested beyond measure exhausts the stack of a recursive parser).
- Do not trust the declared
Content-Typewithout checking it.
Typical mistakes
- Saying that JSON is "faster" than XML by nature: it is more compact and simpler to process, not a different protocol.
- Not escaping quotes, backslashes and control characters when generating JSON.
- Using
GETfor operations that change data, orPOSTfor everything (level 0). - Always answering
200, even on error, with the error in the body: the status code is part of the contract. - Creating with
POSTwithout returning201andLocation; deleting and returning a body with204. - Believing that REST is a protocol or that "stateless" means "without authentication".
- Putting verbs in URIs (
/createBook); usingPUTfor partial changes (it replaces the whole resource). - Confusing well-formed and valid XML.
Versione ripasso
- Web service. Software service used by other programs over a network, with standard-format messages over HTTP. Needed: data format (XML, JSON), way to express operations (SOAP or REST), transport (HTTP).
- XML. Tree of elements with tags; well formed: one root, nested and closed tags, case-sensitive names, quoted attributes, entities
< > & " ',<![CDATA[ ]]>. Namespaces (xmlns:m="..."); valid = conforms to DTD/XSD. DOM or SAX. Typeapplication/xml. - JSON (RFC 8259). Values: object
{}, array[], string (double quotes, escapes\" \\ \/ \b \f \n \r \t \uXXXX), number,true/false,null. No comments or trailing commas, UTF-8,application/json. Example:{"id":42,"title":"Computer Networks","authors":["Rossi","Bianchi"],"price":29.9,"available":true}.
| XML | JSON | |
|---|---|---|
| size | larger | smaller |
| types | text only (XSD) | numbers, booleans, null, arrays |
| structure | elements, attributes, namespaces | objects and arrays |
| use | SOAP, documents | REST APIs |
- JSON in C. Libraries (
cJSON,jansson) or a minimal extractor for flat objects: handle escapes, check buffers, escape on output (Say "hi"becomes"Say \"hi\"");strstris not a parser. - SOAP. XML messages:
Envelope>Header(optional) +Body; errors in theFaultelement (CodeSender/Receiver,Reason, HTTP status500). Over HTTP:POSTto a single endpoint,Content-Type: application/soap+xml(SOAP 1.1:text/xml+SOAPAction); the operation is in the Body. WSDL describes the service;WS-*standards. Verbose, heavy parsing, suited to enterprise integrations. - REST (Fielding, 2000). Architectural style. Constraints: client-server, stateless (each request self-sufficient), cache, uniform interface (URIs, representations, self-descriptive messages, HATEOAS), layered system, optional code on demand.
| operation | request | success |
|---|---|---|
| list / read | GET /books, GET /books/42 |
200 (or 404) |
| create | POST /books |
201 Created + Location |
| replace | PUT /books/42 (complete representation) |
200/204 |
| partial change | PATCH /books/42 |
200 |
| delete | DELETE /books/42 |
204 No Content |
- Rules. URIs = nouns (
/books/42), filters with query (?author=Rossi). Codes:400,401,403,404,405+Allow,409,415,500. Idempotent:GET,PUT,DELETE;POSTis not. Richardson maturity: 0 singlePOST, 1 resources, 2 methods and codes, 3 HATEOAS. Versions in the URI (/v1/). - REST vs SOAP. REST: style, JSON/XML, HTTP methods on different URIs, errors with status codes, natural cache, lightweight. SOAP: protocol, XML only, everything in
POST, errors asFault, hard to cache, heavy. - Security. HTTPS, validate inputs, limit size and nesting, disable XML external entities (XXE), do not trust
Content-Type. - REST session.
POST /tasks->201 Created,Location: /tasks/1, body{"id":1,"title":"Buy the milk","done":false};GET /tasks/9->404+ JSON error;PUT /tasks/1with{"title":"Milk","done":true}->200;DELETE /tasks/1->204without body. - Idempotence and state.
GET,PUT,DELETEcan be repeated without new effects;POSTcannot. Stateless does not mean unauthenticated: each request carries itsBearertoken, so the service can be replicated behind a load balancer. - Typical mistakes: JSON without escaping;
GETthat modifies; always200;POSTwithout201/Location;204with a body; verbs in URIs;PUTfor partial changes; REST thought of as a protocol; well-formed XML confused with valid.