RESTful web services: When to use HTTP PATCH method

HTTP is a very interesting method but just a few application, SOA or Enterprise Integration developers use all of its capabitities. POST and GET among all HTTP Methods are the most used Method followed by PUT. Yet not very used the PATCH method is very useful and it plays a so specific role that it worth understanding its semantics.

In order to better understand HTTP’s PATCH method let’s have a real-world inspired example. The following figure is a simplified version of a integration project that I’ve been working on.

Users  connect to the cloud-based Payroll System in order to do many activivies such as employee data management.  This system holds the “master data” for employees.

Now imagine everytime an employee data is created or edited in the Payroll System we have to send this new/edited data  (the “1” in the figure) to other systems such as a Sales/Remuneration system (the “2” in the figure), a Performance Appraisal System (the “3” in the figure) and so on (the “4” in the figure).

As described in one of my last posts When to use HTTP Post and HTTP PUT, both POST and PUT create or edit a full Resource Representation, i.e., when you have all of its data.

Bringing it to our Payroll example it means we would create a RESTful web service – in our Tibco ESB – based on POST/PUT  method if the Payroll would send not only the edited Employee data but all its data (all attributes). But that was not the case of the Payroll system I was integrating with. The Payroll sends only the edited data, I mean, if a employee move to another apartment in the same building the payroll would send just the Address’ complement without the street name, city, postal code and so on so forth. That’s why HTTP PATCH was created for!

While in a PUT/POST request, the enclosed entity is considered to be a modified version of the resource stored on the
origin server, and the client is requesting that the stored version be replaced. With PATCH, however, the enclosed entity contains a set of instructions describing how a resource currently residing on the origin server should be modified to produce a new version.

Therefore, the final result of the RESTful web services created in Tibco ESB for this project was:

  • POST /employee/id:  Creates a employee in the Payroll system;
  • PUT /employee/id: Broadcasts a message  so that all other systems replace a full employee data. Actually, this will only be used in the future in my project and we did not created it;
  • PATCH /employee/id: Broadcasts a message  so that all other systems update just a set of a employee’s data.

That’s all for today. I hope you now are able to make a better decision on when to use POST, PUT and PATCH when designing RESTful web services.



RESTful Web Services: When to use POST or PUT?

From time to time I have a discussion with my workmate Carlos Filho and our Architecture team at Infoglobo about the use of POST and PUT when developing RESTful webservices. Such discussion happens because we always get confused on when to use POST and when to use PUT.

The convention I’m going to explain here was not stated by us. It’s a definition made by Leonard Richardson and Sam Ruby in RESTful Web Services (Web services for the real world) published in 2007.

When to use POST

Scenario 1) If the client wants the service to create a resource but the client is not sure how (or don’t know) the resource’s URI is going to look like in advance
For example, let’s say you are designing a Restful web service to deal with Products. A possible solution for a product creation would be…
POST /product
…where you would, let’s say, send a XML representation with all product’s specific attributes.
This way the service would could take either a product ID or a auto-generated code to compose this product’s URI and return this URI in the Location HTTP header response. Therefore, the response header to the POST /product request would have something like…
Location: /product/1234
…where 1234 is the product’s identifier whe talked about.
Scenario 2) If the client wants the service to append a resource to a collection but the client is not sure (or don’t know) how the resource’s URI is going to look like in advance
This is scenario is very similay to the previous one. Considering you have a product catalog you would issue a…
POST /surf-boards-catalog
…and the service would return a Location header such as…
Location: /surf-boards-catalog/product/1234

Tha’s pretty the same as the first scenario.

When to use PUT

Scenario 1) If the client wants the service to update a resource identified by an URI that the  client knows in advance

This is the case where the client is going to use the URI provided by the service. This URI in the one in Location header provided by the service in the response to the POST request that created the resource.

Scenario 2) If the client wants the service to create a resource identified by an URI that the  client knows in advance

When it’s the client who will decide how will be the resource’s URI, and not the service, the client should use PUT. In this scenario, of course the service knows the URI’s pattern but it’s the client who will tell the service what will be each one of the variable URI parts.

We had an example at Infoglobo of such scenario. We created a RESTful web service that will be consumed by iPhone,  iPad and Android applications developed by Infoglobo. The first time the application is opened it will issue a request to this RESTful service to tell it there is a new device where the application was installed.

Each device is identified by an token and each application has a specific identification depending on the device’s operational system. This way we defined that each applilcation would issue a PUT request such as…

POST /application/[app-id]/platform/[platform-id]/device/[device-token]

In this scenario the service doesn’t know in advance all device tokens and we decided not to register or create all applications and platforms in advance. All of it is done in this single request. Although the service knows the URL pattern  it’s up to the client to define how the final URI looks like.

Hope that helps you when designing your next RESTful web service.

SOA Security

Many companies that start walking on the SOA road, end up stumbling upon Security requirements related to the use of the enterprise webservices.

So before choosing security solutions/tecnologies the first 2 things you must ask yourlself are:

  1. What  is critical to buisness and need to be protected?
  2. If i was a bad guy what would i try to exploit and get advantage or create problems for the enteprise?

Probably the awsers to these questions will drive you to choose which of the security concepts you will use on your solution.

Here are the default security concepts you probably will have to address:

Identification : Who receives the message should have a way to identify who sent it

Autentication : Who receives the message needs to check that the sender´s identity  is valid

Authorization: Who receives the message need to know what´s the sender´s acess level.  This can be related with which operations and data are being will be acessable to the sender.

Integrity: The message remains the same during the transmission and arrival to the recipient.

Confidentiality: The message content can not be seen while is being transmitted, with excteption of authorized service.

After selecting which of these concepts you’ll need, its time to choose the best security tecnology that fit your requirements.

The following are some links to examples of such tecnology that can be applied to different architecture layers.

Transport Layer:

  • SSL – Secure Socket Layer
  • TLS – Transport Layer Security
Application layer:
Data layer:
On the next post I will deeply discuss some of these solutions.
Http Request
Get /taas/autor/carlosfilho HTTP/1.1
Http Response
HTTP/1.1 410 Gone

How to install jUDDI on Tomcat by yourself


This week I had to install Apache jUDDI for the purpose of the “Knowledge Organization and WEB 3.0” class which is one of my Master’s degree disciplines at PPGI-UFRJ.

When I went to jUDDI‘s web site I discovered that jUDDI have a embeded Apache Tomcat within it. No problem if I hadn’t already installed Tomcat.

Since I wouldn’t like to have 2 running Tomcat installations I decided to install and deploy jUDDI in my existing Tomcat installation. After a few searches in Google I could not find someone who have already done it. That’s why I decided to write this (not so comprehensive) instructions.

Well, since I have already had a running Tomcat installation you will have to install it. It’s very easy. You can find a lot of HOW TOs around. Therefore, I consider the following prerequisites for my step-by-step installation instructions of jUDDI.


Having properly installed and configured Java and Tomcat we can now start with the other jUDDI‘s prerequisites.

Step 1 – Install MySQL and create a database for jUDDI
  1. Download and install MySQL Community Server 5.5.14. Choose the MSI installer version;
  2. Now let’s create a user and a database for jUDDI…
  3. Execute the MySQL Command Line Client (It’s in Windows’ Program menu);
  4. Execute these 3 commands: “CREATE USER ‘juddi’@’localhost’ IDENTIFIED BY ‘juddi’;“, “CREATE DATABASE juddi;” and “GRANT ALL PRIVILEGES ON juddi.* TO ‘juddi’@’localhost’;“;
Step 2 – Deploy Apache jUDDI
  1. Download jUDDI portal bundle 3.0.4 and unzip it. Although this zip have an embeded Tomcat installation we won’t use it. We’ll need jus some webapps inside it.
  2. Copy the juddiv3, pluto and juddi-portlets folders (they are located inside the webapps folder in the zip file) to Tomcat‘s webapps folder. Again, just as a reference my webapps folder is in C:\Program Files\apache-tomcat-6.0.29\webapps;
  3. Also copy the following libraries from your zip’s juddi-portal-bundle-3.0.4\lib folder to your existing C:\Program Files\apache-tomcat-6.0.29\webapps folder:
    • castor-1.1.1.jar
    • commons-discovery-0.2.jar
    • commons-logging-1.1.jar
    • pluto-container-1.1.7.jar
    • pluto-descriptor-api-1.1.7.jar
    • pluto-descriptor-impl-1.1.7.jar
    • pluto-taglib-1.1.7.jar
    • portlet-api-1.0.jar
    • log4j-1.2.13.jar
Step 3 – Configure MySQL JNDI Resources in Tomcat
  1. Download MySQL Connector/J 5.1.17 (the official JDBC driver for MySQL) and unzip it. Find the mysql-connector-java-5.1.17-bin.jar file and copy it to the lib folder of your existing Tomcat installation. My Tomcat‘s lib is in C:\Program Files\apache-tomcat-6.0.29\lib;
  2. Open the file C:\Program Files\apache-tomcat-6.0.29\webapps\juddiv3\META-INF\context.xml with any text editor and edit it in order to look like this…
      • <?xml version=”1.0″ encoding=”UTF-8″?>
      • <Context>
      • <WatchedResource>WEB-INF/web.xml</WatchedResource>
      • <Resource
      • name=”jdbc/juddiDB
      • auth=”Container” 
      • type=”javax.sql.DataSource” 
      • username=”juddi” 
      • password=”juddi” 
      • driverClassName=”com.mysql.jdbc.Driver” 
      • url=”jdbc:mysql://localhost:3306/juddi”
      • />
      • </Context>
  3. Now a very important thing. There are 3 other files that must be in synch with the context.xml. The resource name juddiDB must be present in the following files relative to C:\Program Files\apache-tomcat-6.0.29\webapps\juddiv3\WEB-INF\:
    • .\web.xml: Set the value of <res-ref-name> as jdbc/juddiDB;
    • .\classes\ Set the property with value juddiDB;
    • .\classes\META-INF\persistence.xml: Set the persistence-unit‘ name to juddiDB, set <non-jta-data-source> value to java:comp/env/jdbc/juddiDB and make sure there is a <property name=”openjpa.jdbc.DBDictionary” value=”mysql“/> element in it.

Step 4 – Add users and roles to Tomcat

  1. Open C:\Arquivos de programas\apache-tomcat-6.0.32\conf\tomcat-users.xml and make sure it looks like this one:

<?xml version=’1.0′ encoding=’utf-8′?>
<role rolename=”pluto“/>
<role rolename=”tomcat”/>
<role rolename=”manager”/>
<user username=”root” password=”root” roles=”pluto,tomcat,manager”/>
<user username=”uddi” password=”uddi” roles=”pluto,tomcat,manager”/>
<user username=”sales” password=”sales” roles=”pluto,tomcat,manager”/>
<user username=”marketing” password=”marketing” roles=”pluto,tomcat,manager”/>
<user username=”tomcat” password=”tomcat” roles=”manager”/>

Step 5 – Enjoy your brand new Registry

Now start Tomcat and open your web browser at http://localhost:8080/juddiv3/. You should see a Apache jUDDI‘s welcome page like this one…
The Apache jUDDI's welcome page
The Apache jUDDI's welcome page

…or like the following one if you click on the jUDDI Portal link

Pluto: The jUDDI portal
Pluto: The jUDDI portal

Now you may for example connect to juddi MySQL database and execute the command “show tables;” just to list all tables created by the jUDDI installation process.

Some very important notes:

  • Of course the instructions on this post are not perfect for a production environment. I installed everything in my windows development sandbox. If you are installing it for a production environment I strongly recommend you not to use the same password as the login name of the MySQL user. Another thing is to change the default jUDDI Authentication.
  • It’s possible to do the same thing for a Linux environment. Just follow the instructions having Linux on your mind;

I’ll talk more about Apache jUDDI Registry on a next post.

Stay away from trouble!

Update at 2011-07-23 23:17

After logging in at Pluto you probably will see that the portlets don’t work. It may print some strack trace errors inside the portlet windows or a javascript alert “erro:null” is shown. To solve this problem you’ll have to do the following:

Make sure the file of webapps/juddiv3 and webapps/uddi-portlets have the same configurations. Therefore, copy webapps/juddiv3/WEB-INF/classes/ to webapps/uddi-portlets/WEB-INF/classes/

Praticando SOA com métodos ágeis: Estória ou História?

Depois de ler o post do Carlos Filho sobre o quadro Kanban para governança SOA que usamos na Infoglobo, lembrei de uma dúvida que sempre pairou sobre mim nos plannings e daily meetings: O correto é usar o termo “estória” ou “história”?

Em algum momento da minha vida lembro de alguém ter me falado ou eu ter lido em algum lugar que o termo “estória” não existia mais e que o termo “história” teria acumulado seu significado. Ao pesquisar no pai dos burros da era do conhecimento (leia-se Google), nunca achei uma fonte confiável que fornecesse uma resposta satisfatória.

Diante da dúvida, na última semana tive a idéia de perguntar ao jornalista e editor de opinião do Jornal O Globo, Aluizio Maranhão, que também é coordenador da revisão gramatical, sintática, semântica e tudo mais que você possa imaginar da Lingua Portuguesa no O Globo.

Meu diálogo com ele foi o seguinte:

– Gostaria de saber se “Estória” foi eliminada do Português ou não? Tempos atrás lembro de ter lido em algum lugar que “História” acumularia o significado de “Estória”. É verdade?

– É. “estória” caiu em desuso… Agora é tudo “história” ou “História”…

– Mas “caiu em desuso” não significa que tenha sido abolido como se fosse parte de uma “reforma gramatical”. Eu posso usar mas não vai estar mais “na moda”. Seria isso?

– Quando você vai no Aurélio é dito que é o mesmo que “história”. Melhor não usar.

Ou seja, ao praticar métodos ágeis e até mesmo no dia a dia, use sempre o termo história (ou História).

Ontologia para SOA

Durante a disciplina Fundamentos da Modelagem no curso de Mestrado do PPGI-UFRJ, fiz uma análise da ontologia de domínio para a Arquitetura Orientada a Serviços, a Ontologia SOA, criada pelo The Open Group. Além disso, apliquei alguns conceitos da UFO – Unified Foundational Ontology propostos por Giancarlo Guizzardi em “Ontological Foundations For Structural Conceptual Models” com o objetivo de criar uma nova modelagem para  Ontologia SOA. A figura abaixo mostra o diagrama que representa parte da modelagem resultante dessa análise e da aplicação da UFO.

Ontologia SOA
Modelagem proposta para a Ontologia SOA do The Open Group

Por diversos motivos a criação de ontologias de domínio, como é o caso da Ontologia SOA, baseadas em ontologias de fundamentação é de extrema importância. Isso por que as ontologias de fundamentação permitem o estabelecimento de ontologias de domínio mais consistentes, expressivas e semanticamente mais ricas.

A modelagem resultante dessa análise atinge o objetivo proposto inicialmente uma vez que ela torna mais explícito uma série de conceitos que na modelagem original da Ontologia SOA, feita pelo The Open Group, estavam implícitos ou apenas descritos em linguagem natural, no caso a língua Inglesa. Dessa forma, os praticantes da Arquitetura Orientada a Serviços poderão se beneficiar dessa nova modelagem já que ela permite um melhor entendimento dos conceitos da Arquitetura Orientada a Serviços e consequentemente um maior alinhamento entre seus praticantes.

Outro aspecto relevante da modelagem proposta é que ela representa um passo a mais em direção à implementação de SOA orientada a modelo (model-driven SOA implementation), o que facilita ainda mais a adoção de SOA.

Leia o meu artigo na íntegra em Obs: É necessário um conhecimento mínimo sobre UFO para uma melhor entendimento do artigo.