Author: Oriol Rius

Some recommendations about RESTful API design

Reading time: 9 – 15 minutes

I want to recommend to you to watch the YouTube video called RESTful API design of Brian Mulloy. In this post I make an small abstract of the most important ideas of the video, of course from my point of view:

  • Use concrete plural nouns when you are defining resources.
  • Resource URL has to be focused in access collection of elements and specific element. Example:
    • /clients – get all clients
    • /clients/23 – get the client with ID 23
  • Map HTTP methods to maintein elements (CRUD):
    • POST – CREATE
    • GET – READ
    • PUT – UPDATE
    • DELETE – DELETE
  • Workaround, if your REST client doesn’t support HTTP methods, use a parameter called ‘method’ could be a good idea. For example, when you have to use a method HTTP PUT it could be changed by method HTTP GET and the parameter ‘method=put’ in the URL.
  • Sweep complexity behind the ‘?’. Use URL parameters to filter or put some optional information to your request.
  • How to manage errors:
JSON response example can be like this:<br><pre>{ 'message':'problem description', 'more_info':'http://api.domain.tld/errors/12345' }</pre><br>

Workaround, if REST client doesn’t know how to capture HTTP error codes and raise up an error losing the control of the client, you can use HTTP response code 200 and put ‘response_code’ field in JSON response object. It’s a good idea use this feature as optional across URL parameter ‘supress_response_code=true’.

Versioning the API. Use a literal ‘v’ followed by an integer number before the resource reference in the URL. It could be the most simple and powerful solution in this case. Example: /v1/clients/

The selection of what information will be returned in the response can be defined in the URL parameters, like in this example: /clients/23?fields=name,address,city

Pagination of the response. Use the parameters ‘limit’ and ‘offset’, keep simple. Example: ?limit=10&offset=0

Format of the answer, in this case I’m not completely agree with Brian. I prefer to use HTTP header ‘Accept’ than his proposal. Anyway both ideas are:

  • Use HTTP header ‘Accept’ with proper format request in the answer, for example, ‘Accept: application/json’ when you want a JSON response.
  • or, use extension ‘.json’ in URL request to get the response in JSON format.
  • Use Javascript format for date and time information, when you are formatting JSON objects.

Sometimes APIs need to share actions. Then we can’t define an action with a noun, in this case use verb. Is common to need actions like: convert, translate, calculate, etc.

Searching, there are two cases:

  • Search inside a resource, in this case use parameters to apply filters.
  • Search across multiple resource, here is useful to create the resource ‘search’.
  • Count elements inside a resource, simply add ‘/count’ after the resource. Example: /clients/count
  • As far as you can use a single base URL for all API resources, something like this: ‘http://api.domain.tld’.
  • Authentication, simply use OAuth 2.0

To keep your API KISS usually it’s a good idea develop SDK in several languages, where you can put more high level features than in API.

Inside an application each resource has its own API but it’s not a good idea publish it to the world, maybe use a virtual API in a layer above it’s more secure and powerful.

Changing Ubuntu CLI language

Reading time: 2 – 4 minutes

My mother tongue is Catalan and of course I speak and understand Spanish very well, but when I’m using a Linux CLI it’s impossible to be agile if the interface is not in English. Then when I need to change Ubuntu interface to English I modify the file /etc/default/locale: 

LANG=en_US.UTF-8
LANGUAGE="en_US:en"

Avui el blog fa 12 anys

Reading time: < 1 minute Avui el blog ha arribat a la nova fita dels 12 anys. Cal dir que ja fa anys que pobret esta tocat ja que les obligacions impedeixen trobar temps pels hobbies; tot i amb això, pel que a mi respecte el considero més viu que mai. La raó és ben senzilla tinc més d'un instint al dia d'escriure coses que finalment no s'acaba podent materialitzar degut a la quantitat de temps que cal dedicar a cada entrada. pastis 12 aniversari del blog

Així doncs, amb els meus millors desitjos i esforços continuaré treballant i esforçant-me dia a dia per canviar aquesta dinàmica, gràcies a tots els que em seguiu.

Ejercicio para amenazas no físicas

Reading time: 4 – 6 minutes

Esta semana estoy terminando la lectura del libro “Ahora YO, ¿y si creas tu propio futuro en lugar de encontrártelo?” del Dr. Mario Alonso Puig. Al finalizar el libro me gustaría hacer una pequeña reseña de los muchos e interesantes contenidos que se nos presentan. Pero ahora mismo lo que me gustaría hacer es un pequeño resumen a modo de bloc de notas de un fragmento de su libro donde se nos explica qué hace que situaciones que no son de peligro físico activen nuestros mecanismos de defensa y cómo podemos cambiar nuestras reacciones ante estas circunstancias.

A menudo podríamos decir que vivimos en una constante tensión porqué de forma simultánea tenemos que proteger el cuerpo físico, mostrar la imagen quien se espera que seamos y esconder la imagen de lo que tememos ser. Como se puede imaginar este trabajo produce un importante desgaste y acaba repercutiendo en nuestra vitalidad y salud. A menudo se habla del miedo al cambio, hoy en día rara vez este miedo tiene que ver con la supervivencia física. Pero si que acostumbra a tener una fuerte relación con la imagen de nosotros que queremos proteger.

Así pues la estrategia que se nos propone en el libro sobre la sensación de amenaza que sentimos al proteger nuestra imagen. Cabe recordar que cuando se siente una amenaza física se activan unos mecanismos de ataque, huida y bloqueo. Estos mecanismos han sido muy útiles a lo largo de la evolución para protegernos de las amenazas físicas pero cuando entramos en estados de amenaza por temas no físicos estos mecanismos instintivos no nos sirven de nada, al contrario, nos perjudican.

Una estrategia para evitar estas reacciones es:

  1. Poner en marcha dos elementos. El elemento mental es la aceptación y el físico el control de la respiración. Al sentir miedo porqué creemos que nuestra imagen esta amenazada, el miedo a la crítica, desilusionar a otros, al que dirán, etc. En estas situaciones la aceptación consiste en hacer el ejercicio de observarnos desde fuera, proyectar nuestra imagen vista desde fuera para observar cuales son nuestras reacciones. Observando las reacciones del cuerpo, cambios en la respiración, aumento de la tensión. Se trata de establecer un distanciamiento entre las emociones que estamos experimentando y el hecho de ser también observadores de estas reacciones como si no fueran propias. A este proceso de observación se le llama meta-atención.
  2. Control de la respiración. Cuando el miedo se apodera de nosotros el primer elemento que cambia es la respiración. A menudo esta se acelera o por el contrario dejamos de respirar es la llamada taquipnea. Para lograr tomar el control podemos ir cogiendo aire de manera consciente y después ir soltándolo con una espiración más larga que la inspiración. Es importante sentir que el abdomen se hincha. Cuando vayamos notando que el control sobre la respiración aumenta podemos decir la palabra uno al inspirar y también al espirar. Llegados a este punto debemos imaginar que un aire de color azul entra por nuestra nariz, llena los pulmones y finalmente llega a los riñones.

Es interesante saber porqué este ejercicio funciona. La respiración controlada y acompasada manda un mensaje al cerebro de que todo va bien. Al decir la palabra uno al inspirar y espirar obliga al cerebro a concentrarse en la respiración dejando sin espacio a aquello que nos ocupa. El color azul es procesado por el hemisferio derecho del cerebro y este lo procesa como una señal de tranquilidad y armonía. No hay que olvidar que los miedos son en gran parte fruto de nuestro inconsciente y la forma más rápida de conectar con esta parte de nuestro ser es a través del hemisferio derecho.

En una segunda fase la pregunta que nos deberíamos hacer es: “¿qué me estoy haciendo para sentirme así?” la respuesta a esta pregunta debemos dejar que nos llegue desde el inconsciente. Debemos estar muy atentos y abiertos. Porqué en el inconsciente hay dos fuerzas una que nos anula y otra que nos ayuda. La que nos anula se ha ido alimentando de los pensamientos tóxicos que hemos recogido de nuestro entorno y de la cultura.

Para acabar estas notas quiero parafrasear el siguiente concepto: “Quien de verdad es compasivo entiende que todo el daño que nos causamos los hombres a nosotros mismos y a los demás no es por una maldad intrínseca, sino porque vivimos asustados, nos sentimos acorralados y eso nos torna intolerantes y agresivos.

Viatge de noces: Japó i Maldives

Reading time: 4 – 7 minutes

Com que encara no he m’he pogut refer al 100% dels problemes tècnics que han afectat a un servidor que va fallar just abans de marxar al viatge de noces encomptes de fer la ressenya del viatge al Wiki la faré al blog directament.

Així doncs, faig un petit resum del que hem estat fent en la lluna de mel i ús poso quatre fotos per fer boca.

Dia 1 (10-11/5/2012) – Torrelavit > Barcelona > Doha > Osaka > Kyoto

L’objectiu d’aquest dia pràcticament només era anar des de casa fins a l’hotel de Kyoto (Karasuma Kyoto Hotel). Així doncs, viatjant amb Qatar Airways i fent escala a Doha varem arribar fins a Osaka on gràcies alJapan Rail Pass poguerem desplaçar-nos fins l’estació central de Kyoto. Allà després d’un munt d’hores de viatge i carregats de maletes agafarem un taxi fins l’hotel. Podriem haver-ho fet en metro però per ser el primer dia varem decidir anar a lo senzill.

Dia 2 (12/5/2012) – Kyoto

El primer dia a Kyoto ens ho varem prendre molt en serio i visitarem el següent:

Dia 3 (13/5/2012) – Kyoto

El segon dia a Kyoto:

Dia 4 (14/5/2012) – Kyoto > Tokyo

Al migdia sortirem amb el Shinkansen des de l’estació de tren de Kyoto fins a la de Tokyo. Allà agafarem el metro en hora punta fins a Shinjuku. Tota una experiència anar en un metro com a sardines i carregats amb les maletes. Al arribar a Tokyo pràcticament ja era de nit i arribarem a l’hotel Keio Plaza on ens van regalar una habitació superior per estar en viatge de noces.

Dia 5 (15/5/2012) – Tokyo

Primer dia de visites per Tokyo:

Dia 6 (16/5/2012) – Tokyo

Segon dia:

Dia 7 (17/5/2012) – Tokyo

Tercer dia per la capital:

Dia 8 (18/5/2012) – Tokyo Narita > Kuala Lumpur > Malé

Amb tren sortirem directament de l’estació de Shinjuku, molt aprop de l’hotel fins al aeroport de Narita. Allà avió amb Malaysia Airlines fins a Kuala Lumpur on ferem escala fins arribar a Malé, capítal de Maldives prop de la mitja nit. Com que era massa tard per agafar un hidroavió fins a l’hotel Kuramathi ferem nit a un hotel al costat de l’aeroport: Hotel Hulhule.

Dia 9 (19/5/2012) – Malé > Hotel Kuramathi

A primera hora del matí i després d’un bon esmorzar agafarem l’hidroavió fins a l’hotel Kuramathi, on començarem l’etapa de relax del viatge de noces. Què podem explicar de passar 4 nits i 4 dies i mig en una habitació de 90 metres quadrats sobre l’aigua, amb banyera d’hidromassatge a la terrassa i totes les comoditats que es poden imaginar. Tot això dins d’una illa on només hi ha l’hotel i on tens tots els serveis i comoditats que es poden imaginar només pensades per passar uns dies de somni.

Dia 14 i 15 (23/5/2012) – Hotel Kuramathi > Malé > Doha > Barcelona > Torrelavit

Sortirem de l’hotel a les 15h aproximadament, així doncs, com no podia ser d’altre forma aprofitarem fins a l’últim minut el privilegi de poder disfrutar la illa i els serveis de l’hotel. Després de nou amb l’hidroavió fins a Malé, allà amb Qatar Airways fins a Barcelona fent escala a Doha.

Resum en fotos

[nggallery id=”1″]

Avui en faig 35!

Reading time: 1 – 2 minutes

Encara dintre d’aquest núvol que m’envolta des de fa setmanes i que no em deixa tocar de peus a terra avui és un altre dia molt especial en la meva vida, avui compleixo 35 anys. No és cap número màgic com els 18 o els 30. Però avui realment sento que tot el que m’envolta és màgic; la família, els amics i el més màgic de tot és la connexió que sento amb el meu interior. Tinc la sensació d’estar en pau en mi mateix i això ús asseguro que és el millor regal que he experimentat mai. La veritat és que ara mateix no puc demanar res a la vida, així doncs només puc seguir donant i compartint tot allò de que disposo. Aprendre que la felicitat és un estat que s’ha de saber disfrutar durant el caminar cap a l’objectiu que manté l’il·lusió i que sostenta la passió amb la que s’afronten les accions diaries. Tot plegat fa que continui afrontant els dies amb un fantàstic somriure als llavis.

9 anys des de que vaig tornar a neixer

Reading time: 2 – 3 minutes

Avui es compleixen 9 anys del meu accident que em podria haver costat la vida, sempre m’agrada escriure un article recordant el moment i mostrant una foto de com va quedar el cotxe.

accident bmw

Aquest any el fet és més emotiu que mai ja que després del punt d’inflexió que va suposar per mi aquest segona oportunitat me n’adono que he canviat molt les meves preferencies vitals i això em fa sentir molt bé. De fet, amb l’última re-organització del blog es pot veure que a més del meu interés per la tecnologia es diferencia clarament un apartat dedicat al creixement personal i un altre per tractar temes personals, com aquest mateix article.

Però no només el blog és un gran exemple del meu canvi interior, el passat 29 d’abril vaig contraure matrimoni amb l’Estefania una persona que m’ha ajudat a tenir un punt de vista molt diferent a la vida; on els aspectes més competitius de la nostre societat han obert un espai a altres parts més emocionals que m’ajuden a mantenir l’equilibri en el meu dia a dia. Quan després de tots aquests anys de treball personal arribes en un punt d’equilibri entre la part mental, emocional, espiritual i física tot plegat té un efecte revitalitzant que t’ajuda a afrontar el dia a dia amb un somriure als llavis.

L’última prova me l’ha posat la vida aquest darrer dia 1, dia en el que un dels meus servidors personals m’ha donat un ensurt que paliar els efectes em costarà encara moltes setmanes de feina i esforç, tan energètic com econòmic. Però el difícil, o l’interessant, és saber afrontar aquesta situació professional sense que m’afecti el moment tan dolç que estic vivint en la meva vida personal. Dit d’altre forma, el interessant és aconseguir que aquest contra-temps tècnic no tingui efectes sobre el viatge de noces que comença aquest proper dijous. Això és el que em fa estar més content de la meva evolució d’aquests 9 anys.

No penseu pas que estic dient que he arribat al final del meu camí, al contrari, he descobert que l’èxit no el trobaré al final del camí sinó disfrutant del dia a dia pel fet de poder viure el camí que he escollit. Per no allargar-me massa acabaré l’article amb una cita:

La vida és un joc, no et prenguis res seriosament.

TED: Jill Bolte Taylor – El derrame de iluminación

Reading time: 2 – 3 minutes

Hoy he disfrutado de este video de TED; es la primera vez que referencio este servicio pero seguro que no será la última.

Quiero recomendaros este video porqué hace una reflexión sobre cómo nos hace percibir nuestro interior y exterior los dos emisferios del cerebro. Creo que son 20min de iluminación que no puedo dejar de recomendaros.

Deseo que os guste y os llene tanto como lo ha hecho conmigo.

Deep inside AMQP

Reading time: 5 – 8 minutes

In the next lines I’ll describe with more details the properties and features of AMQP elements. It won’t be an exhaustive description but in my opinion more than enough to start playing with AMQP queues.

Channels

When producers and consumers connects to the broker using a TCP socket after authenticating the connection they establish a channel where AMQP commands are sent. The channel is a virtual path inside a TCP connection between this is very useful because there can be multiple channels inside the TCP connection each channels is identified using an unique ID.

An interesting parameter of a channel is confirmation mode if this is set to true when messages delivered to a exchange finally gets their queues the producer receives an acknowledge message with an UID of the message. This kind of messages are asynchronous and permits to a producer send the next message when it is still waiting the ACK message. Of course if the message cannot be stored and it is lost the producer receives a NACK (not acknowledged) message.

Producers

Maybe this is the most simple part of the system. Producers only need to negotiate the authentication across a TCP connection create a channel and then publish all messages that want with its corresponding routing key. Of course, producers can create exchanges, queues and then bind them. But usually this is not a good idea is much more secure do this from consumers. Because when a producers try to send a message to a broker and doesn’t have the needed exchange then message will be lost. Usually consumers are connected all time and subscribed to queues and producers only connect to brokers when they need to send messages.

Consumers

When a consumer connects to a queue usually uses a command called basic.consume to subscribe the channel to a queue, then every time subscribed queue has a new message it is sent to consumer after last message is consumed, or rejected.

If consumer only want to receive one message without a subscription it can use the command basic.get.This is like a poll method. In fact, the consumer only gets a message each time it sends the command.

You can get the best throughput using basic.consume command because is more efficient than poll every time the consumer wants another message.

When more than one consumer was connected to a queue, messages are distributed in a round-robin. After the message is delivered to a consumer this send an acknowledge message and then queue send another message to next consumer. If the consumer sends a reject message the same message is sent to next consumer.

There are two types of acknowledgements:

  • basic.ack: this is the message that sends consumer to queue to acknowledge the reception of a message
  • auto_ack: this is a parameter we can set when consumer subscribes to a queue. The setting assumes ACK message from consumer and then queue sends next message without waiting the ACK message.

The message basic.reject is sent when the consumer wants to reject a received message. This message discards the message and it is lost. If we want to requeue the message we can set the parameter requeue=true when sent a reject message.

When the queue is created there can be a parameter called dead letter set to true, then consumer rejects a message with the parameter requeue=false the message is queued to a new queue called  dead letter. This is very useful because after all we can go tho that queue an inspect the message rejection reason.

Queues

Both consumers and producers can create a queue using queue.declare command. The most natural way is create queues from consumers and then bind it to an exchange. The consumers needs a free channel to create a queue, if a channel is subscribed to a queue, the channel is busy and cannot create new queues. When a queue is created usually we use a name to identify the queue, if the name is not specified it’s randomly generated. This is useful when create temporary and anonymous queues for RPC-over-AMQP.

Parameters we can set when create a new queue:

  • exclusive – this setting makes a queue private and is only accessible from your application. Only one consumer can connect to a queue.
  • auto-delete – when last consumer unsubscribes from queue the queue is removed.
  • passive – when create a queue that exists the server returns successfully or returns fail if parameters don’t match. If passive parameter is set and we create a queue that exists always returns success but if the queue doesn’t exist it is not created.
  • durable – the queue can persist when the services reboots.

Exchange and binding

In the first post of the serie we talked about different exchange types as you can remember these types are: direct, fanout and topic. And the most important parameter to set when producer sends a message is the routing key this is used to route the message to a queue.

Once we have declared an exchange this can be related with a queue using a binding command: queue_bind. The relation between them is made using the routing key or a pattern based in routing key. When exchange has type fanout the routing key or patterns are not needed.

Some pattern examples can be: log.*, message.* and #.

The most important exchange parameters are:

  • type: direct, fanout and topic.
  • durable: makes an exchange persistent to reboots.

Broker and virtual hosts

A broker is a container where exhanges, bindings and queues are created. Usually we can define more than one virtual brokers in the same server. Virtual brokers are also called virtual hosts. The users, permissions and something else related to a Broker cannot be used from another one. This is very useful because we can create multiple brokers in the same physical server like multi-domain web server and when some of this virtual hosts is too big it can be migrated to another physical server and it can be clustered if it is required.

Messages

An AMQP message is a binary without a fixed size and format. Each application can set it’s own messages. The AMQP broker only will add small headers to be routed among different queues as fast as possible.

Messages are not persistent inside a broker unless the producer sets the parameter persistent=true. In the other way the messages needs to be stored in durable exchanges and durable queues to persist in the broker when it is restarted. Of course when the messages are persistent these must be wrote to disk and the throughput will fall down. Then maybe sometimes create persistent messages is not a good idea.

 

 

El mejor año de tu vida

Reading time: 1 – 2 minutes

Este mes de enero leí el libro “El mejor año de tu vida” de Mónica Fusté. Un libro que ya estube recomendando a través de twitter. Después de leer el libro y a modo de notas personales hice un mapa mental que hoy me he decidido a traducir al castellano y a compartir con todos vosotros.

mind map del libro "el mejor año de tu vida"
mind map del libro "el mejor año de tu vida"

Añadir que este mapa mental no sustituye para nada la lectura del libro. Pero si que después de leerlo a mi me ha sido muy útil tenerlo a mano para recordar conceptos fundamentales del viaje interior que estoy haciendo.

Scroll to Top