Xitrum Learning notes 04-restful APIs

Source: Internet
Author: User
Tags representational state transfer

RESTful API:

A restful API called RESTful APIs, a unified mechanism for communication between different front-end devices and the backend

What is a restful architecture:

(1) Each URI represents a resource;

(2) between the client and the server, the transmission of such resources of some kind of performance layer;

(3) The client uses HTTP verbs (get to get resources, post is used to create new, update resources, put is used to update resources, delete is used to remove resources), server-side resources to operate, to achieve "performance layer State transformation."

REST--Representational State Transfer
The full name is Resource representational State Transfer: In layman's terms, resources are transferred in a certain form in the network. Break apart:
Resource: The resource, the data (the core of the network mentioned above). such as newsfeed,friends and so on;
Representational: Some form of expression, such as with Json,xml,jpeg;
State Transfer: status change. Implemented via HTTP verbs.

Reference Documentation:

Http://www.ruanyifeng.com/blog/2011/09/restful--Understanding the RESTful architecture

Http://www.ruanyifeng.com/blog/2014/05/restful_api.html--restful API Design Guide

https://www.zhihu.com/question/28557115

Xitrum RESTful API Example:

Import Xitrum. ActionImport  xitrum.annotation.get@get ("articles")classextends  Action {  def execute () {...}} @GET ("Articles/:id")classextends  Action {  def execute () {...}}

POST, put, PATCH, DELETE, and options are used in the same way as get, and the Xitrum automatically handles the head as a get with an empty response body.

For HTTP clients that do not support put and delete, simulate put and delete actions by sending a post with _method=put and _method=delete in the response body

When the Web application starts, Xitrum scans all annotations, creates a path table and prints it in the console, such as:

[INFO]                              Normal routes:get/articles/new Demos.action.ArticlesNewGET/               Demos.action.siteindexpost/api/articles Demos.action.apiarticlescreatepatch/api/articles/:id        Demos.action.apiarticlesupdatedelete/api/articles/:id Demos.action.ApiArticlesDestroyGET /articles/:id<[0-9]+>.:format Demos.action.articlesdotshow[info] Sockjs routes:/sockjschat demos.acti On. Sockjschatactor websocket:true, Cookie_needed:false/filemonitorsocket demos.action.FileMonitorSocket Websocket:tru E, Cookie_needed:false[info] Error routes:404 demos.action.NotFoundError500 Demos.action.servererror[info] Xitrum Routes:get/xitrum/xitrum-3.28.3.js Xitrum.jsget/xitrum/swagger.json Xitrum.routing.swaggerjsonget/xitrum/swagg  Er xitrum.routing.swaggeruiget/xitrum/metrics/viewer xitrum.metrics.xitrummetricsviewer[info] xitrum SockJS Routes:/xitrum/metRics/channel Xitrum.metrics.XitrumMetricsChannel Websocket:true, Cookie_needed:false 

Paths (Routes) are automatically collected, no additional declarative work is required, and we can rebuild URLs in a type-safe manner

Route cache (Path caching)

To speed up the boot, the path is cached in the file Routes.cache. In the development process, the paths in the. class under the target path are not cached.

If you change the dependent library that contains the path, you need to delete the Routes.cache. Routes.cache should not be submitted to the Code repository

Defining route priorities using first and last
Import xitrum.annotation. {GET, first} @GET ("Articles/:id")classextends  Action {  // This route have higher priority than "Articlesshow" above@GET ("articles/new")class  Extends  Action {  def execute () {...}}

This way, when you define the routes table, articlesnew the corresponding path to the front. Last annotation is used the same as first

One action has multiple paths
@GET ("image", "Image/:format")classextends  Action {  def execute () {    = Paramo ("format"). Getorelse ("PNG")    //  ...   }}
Some numbers and regular expressions in the path
@GET ("Articles/:id", "Articles/:id.:format")classextends  Action {  def execute () {    = Param[int] ("id")    = Paramo ("format"). Getorelse ("HTML")    //  ...   }} @GET ("articles/:id<[0-9]+>") ...

Get the rest of the path

/Slash is a special character, so it cannot appear in the parameters of the path. If you need a slash in the argument, put the argument at the end and use an asterisk, for example

GET ("service/:id/proxy/:*")

This will match/service/123/proxy/http://foo.com/bar.

The section that gets:* can be implemented with the following code

Val url = param ("*")//'ll Be "Http://foo.com/bar"

Link to an action via hyperlink marker <a>

The wording in the view

<a Href={url[articlesshow] ("id", myarticle.id)}>{myarticle.title}</a>
Redirect and forward to another action redirect and forward:

Forwarding is the server behavior, and redirection is the client behavior. Why do you say that, it depends on the workflow of two actions:

Forwarding process: The client browser sends an HTTP request-the Web server accepts this request-a method inside the container to complete the request processing and forwarding actions within the containers-the target resource is sent to the customer; here, the forwarded path must be a URL under the same Web container. It cannot be turned to other web paths, and the middle passes through the request within its own container. In the customer browser path bar is still the path of its first access, that is, the customer does not feel that the server is forwarded. The forwarding behavior is that the browser makes only one access request.

REDIRECT process: The client browser sends an HTTP request--"The Web server accepts a 302 status code response and corresponds to a new location to the client's browser--" The client browser finds that the 302 response, then automatically sends a new HTTP request, The request URL is the new location address-the server looks for resources based on this request and sends them to the customer. Here the location can be redirected to any URL, since the browser has re-issued the request, there is no concept of request delivery. The client browser path bar displays its redirected path, and the customer can observe the change of address. The redirect behavior is that the browser has made at least two access requests.

REDIRECT for Xitrum:
ImportXitrum. ActionImportxitrum.annotation. {GET, POST} @GET ("Login")classLogininputextendsAction {def execute () {...}} @POST ("Login")classDologinextendsAction {def execute () {...    //After login Success Redirectto[adminindex] () }} @GET ("Admin")classAdminindexextendsAction {def execute () {...    //Check If the user has not logged in, redirect him to the login page Redirectto[logininput] ()//Generate a new request }}

Redirect to current action can use the Redirecttothis () method

Forward to another action

Forwardto[anotheraction] ()//Do not generate a new request

How to determine whether a requirement is an AJAX requirement

With Isajax

//  In an actionval msg = "A message"if  (isajax)  jsRender ("alert (" + jsescape (msg) + ")")else  respondtext (msg)
What's csrf about CSRF

Cross-site request forgery, cross-site solicitation forgery, also known as: one click Attack/session Riding, abbreviated as: CSRF/XSRF.

A hazard is when a user logs on to a trusted site A, and after a local cookie is generated, visits the dangerous site B without logging out a.

This way an attacker could steal your identity and send a malicious request on site A on your behalf. For example, you can steal your account, send mail as you, buy goods, etc.

Defense CSRF

For non-GET requests, xitrum defaults to web App defense CSRF

After adding Anticsrfmeta to the View Code,

Import Xitrum. Actionimportextends  action {  = doctype.html5 (            {Anticsrfmeta}        {xitrumcss} {        jsdefaults}         <title>welcome to xitrum</title>              {Renderedview}        {Jsforview}        </body>      )}

Corresponding to the head of the HTML page, the resulting

<meta name= "Csrf-token" content= "5402330e-9916-40d8-a3f4-16b271d583be"/>

If Xitrum.js is added to the view template, the token is automatically included in all non-get AJAX requests as X-csrf-token header information issued by jquery.

You can add xitrum.js to the view by calling the Jsdefaults method in the view.

Another way to add xitrum.js to a view is to add the following code to the view

<script type= "Text/javascript" src={url[xitrum.js]}></script>

Xitrum gets the CSRF token from the X-csrf-token request header, and if this does not exist, Xitrum is obtained from the Csrf-token request body parameter (not from the parameters in the URL)

If the Csrf-token meta tag and xitrum.js are not used in the head, you need to add anticsrfinput or Anticsrftoken in the form

Form (method= "POST" Action={url[adminaddgroup]})!  = anticsrfinput//or form (method= "POST" action={url[ Adminaddgroup]})  input (type= "hidden" name= "Csrf-token" Value={anticsrftoken})

When you need to skip the Csrf check, mix the trait xitrum. Skipcsrfcheck into action, such as

Import Xitrum. {Action, Skipcsrfcheck} Import  extends  Action with Skipcsrfcheck@post ("api/positions")class  Extends  Api {  def execute () {...}} @POST ("Api/todos")classextends  API {  def execute () {...}}
Change the paths that have been collected

Xitrum automatically collects the action path when the Web app starts, you can change the path by using Xitrum.Config.routes in Boot.scala

ImportXitrum. {Config, server}object Boot {def main (args:array[string]) {//You can modify routes before starting the serverVal routes =config.routes//Remove routes to a action by its classRoutes.removebyclass[myclass] ()if(demoversion) {//Remove routes to actions by a prefixRoutes.removebyprefix ("Premium/features")      //This also worksRoutes.removebyprefix ("/premium/features")    }    ... Server.start ()}}

Get the entire request content

In general, if the requested content type is not application/x-www-form-urlencoded, you may need to parse the entire request content in your code

// To get it as a string:val body = requestcontentstring//toget it as JSON:Requestco Ntentjvalue//  = json4s (http://json4s.org) jvalueval myMap = Xitrum.util.serideseri.fromjvalue[map[string, Int]] (myjvalue)

If you want full control, use Request.getcontent, which returns a value of type Bytebuf

Xitrum Learning notes 04-restful APIs

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.