Function registerRestInterface
Generates registers a REST interface and connects it the the given instance
.
Each method is mapped to the corresponing HTTP verb. Property methods are mapped to GET/PUT and all other methods are mapped according to their prefix verb. If the method has no known prefix, POST is used. The following table lists the mappings from prefix verb to HTTP verb:
Prefix | HTTP verb |
---|---|
get | GET |
query | GET |
set | PUT |
put | PUT |
update | PATCH |
patch | PATCH |
add | POST |
create | POST |
post | POST |
A method named 'index' is mapped to the root URL (e.g. GET /api/). If a method has its first parameter named 'id', it will be mapped to ':id/method' and 'id' is expected to be part of the URL instead of a JSON request.
Any interface that you return from a getter will be made available with the base url and its name appended.
Prototype
void registerRestInterface(T)(UrlRouter router, T instance, string url_prefix = "/", MethodStyle style = MethodStyle.LowerUnderscored)( UrlRouter router, T instance, string url_prefix, MethodStyle style );
Examples
The following example makes MyApi available using HTTP requests. Valid requests are:
- GET /api/status → "OK"
- GET /api/greeting → "<current greeting>"
- PUT /api/greeting ← {"text": "<new text>"}
- POST /api/new_user ← {"name": "<new user name>"}
- GET /api/users → ["<user 1>", "<user 2>"]
- GET /api/ → ["<user 1>", "<user 2>"]
- GET /api/:id/name → ["<user name for id>"]
- GET /api/items/text → "Hello, World"
- GET /api/items/:id/index → <item index>
import vibe.d; interface IMyItemsApi { string getText(); int getIndex(int id); } interface IMyApi { string getStatus(); @property string greeting(); @property void greeting(string text); void addNewUser(string name); @property string[] users(); string[] index(); string getName(int id); @property IMyItemsApi items(); } class MyItemsApiImpl : IMyItemsApi { string getText() { return "Hello, World"; } int getIndex(int id) { return id; } } class MyApiImpl : IMyApi { private string m_greeting; private string[] m_users; private MyItemsApiImpl m_items; this() { m_items = new MyItemsApiImpl; } string getStatus() { return "OK"; } @property string greeting() { return m_greeting; } @property void greeting(string text) { m_greeting = text; } void addNewUser(string name) { m_users ~= name; } @property string[] users() { return m_users; } string[] index() { return m_users; } string getName(int id) { return m_users[id]; } @property MyItemsApiImpl items() { return m_items; } } static this() { auto routes = new UrlRouter; registerRestInterface(routes, new MyApiImpl, "/api/"); listenHttp(new HttpServerSettings, routes); }
See Also
RestInterfaceClient
class for a seamless way to acces such a generated API
Authors
Sönke Ludwig
Copyright
© 2012 RejectedSoftware e.K.
License
Subject to the terms of the MIT license, as written in the included LICENSE.txt file.