सामग्री पर जाएँ

लेसन 32 · Web and Applications

Teapot and Zinc: HTTP Services

Learn Zinc, Pharo's HTTP client and server, and Teapot, a small routing layer for REST APIs: GET and POST routes, path parameters, JSON, status codes. Read-only Smalltalk plus a runnable router stand-in.

Pharo ships with Zinc, a complete HTTP library: a client, a server and the message objects that go with them. On top of it sits Teapot, a tiny framework for building REST services with routes, in the style of Sinatra or Express. Together they let you expose Smalltalk objects as a JSON API in a few lines, and call other services as a client.

Neither library runs on this site, so the Smalltalk code is read-only. A JavaScript stand-in later implements a route matcher with path parameters, which is the core of what Teapot does, so you can experiment with routing logic.

Zinc as a client

The client API is short (read-only):

SMALLTALK
ZnClient new get: 'https://example.com/hello'.            "returns the body as a String"

ZnClient new
    url: 'https://example.com/api/books';
    accept: ZnMimeType applicationJson;
    get.

ZnClient new
    url: 'https://example.com/api/books';
    contentWriter: [ :obj | ZnEntity json: (NeoJSONWriter toString: obj) ];
    post: { 'title' -> 'Dune' } asDictionary.

A client object is configurable and reusable: you set the URL, headers, timeouts and body, then send get, post:, put: or delete. Check the response with response code, response isSuccess and response contents. Always set a timeout (timeout: 5) so a hung server cannot freeze your process.

Zinc as a server

A server is one expression (read-only):

SMALLTALK
ZnServer startDefaultOn: 8080.
ZnServer default delegate: (ZnStaticFileServerDelegate new).

Zinc parses the request into a ZnRequest, hands it to a delegate, and writes the ZnResponse you return. That is the low level. Most services use Teapot instead.

Teapot routes

Teapot maps a method and a path pattern to a block (read-only):

SMALLTALK
| teapot books |
books := OrderedCollection new.
teapot := Teapot configure: { #port -> 8080. #debugMode -> true }.

teapot
    GET: '/books' -> [ :req | books asArray ];
    GET: '/books/<id>' -> [ :req | books at: (req at: #id) asInteger ];
    POST: '/books' -> [ :req | books add: req entity contents. TeaResponse created ];
    DELETE: '/books/<id>' -> [ :req | books removeAt: (req at: #id) asInteger. 'deleted' ];
    output: #json;
    start.

Key points:

  • Path parameters like <id> become entries in the request (req at: #id).
  • Query parameters (?page=2) are read with req at: #page ifAbsent: [ 1 ].
  • output: #json serializes the block's return value to JSON, and output: #text or #html choose other formats.
  • Return a TeaResponse to control status codes and headers, for example TeaResponse notFound or TeaResponse created.
  • Filters run before or after matching routes: before: '/*' -> [ ... ] is the place for logging and authentication.
  • Exception handling: exception: KeyNotFound -> [ :ex :req | TeaResponse notFound ] maps errors to HTTP statuses.

Testing a service

You rarely need a real network in tests. Call the server on localhost with a ZnClient inside an SUnit test, stop it in tearDown, and pick a free port. For faster tests, call the route block directly with a prepared request object.

A route matcher you can run

The part of Teapot that is easiest to understand is the matching of paths like /books/<id>. This stand-in compiles patterns into regular expressions, extracts parameters and dispatches to handlers, then returns a status code and a JSON body.

JS Stand-in: a Teapot-style router

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The PUT call returns 404 because no route is registered for that method and path. A production router would answer 405 (method not allowed) when the path exists with another method.

Clients and servers together

JS Stand-in: a client calling the router

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Retrying only server errors is a good default; a 404 will not fix itself. Keep retry counts small and add a delay in real code.

Design notes

  • Keep route blocks thin: convert the request, call a domain object, convert the answer. The domain object can then be tested without HTTP.
  • Return the right status codes: 200, 201 (created), 204 (no content), 400, 404, 500.
  • Version your API paths (/v1/books) from the start.
  • For persistence behind the API, see Persistence with Fuel and Databases. For a browser UI rendered on the server, see Seaside.
sequenceDiagram
  participant C as Client (ZnClient)
  participant T as Teapot route
  participant D as Domain object
  C->>T: GET /books/1
  T->>D: find: 1
  D-->>T: a Book
  T-->>C: 200 {"title":"Emma"}

The route only translates between HTTP and the domain.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What is Teapot built on?

    Teapot adds routing and response helpers on top of the Zinc HTTP server.
  2. 2. How does Teapot expose a path parameter in /books/<id>?

    Path and query parameters are read from the request object.
  3. 3. What should a client set so a hung server does not block forever?

    Always configure a timeout on network calls.
  4. 4. Which status code means a resource was created?

    201 Created is the proper reply to a successful POST that creates something.

Summary

  • Zinc is Pharo's HTTP client and server; ZnClient new get: and post: cover most calls.
  • Teapot maps methods and path patterns such as /books/<id> to blocks, with filters, JSON output and error mapping.
  • Keep routes thin, return correct status codes and test the domain without HTTP.
  • The Smalltalk code is read-only; the router and retry examples are JavaScript stand-ins.

Next: Persistence with Fuel and Databases

अपनी प्रगति ट्रैक करें

मुफ़्त अकाउंट बनाएँ, लेसन पूरे के रूप में चिह्नित करें और किसी भी डिवाइस पर वहीं से शुरू करें जहाँ छोड़ा था।