Pages

Introducing the Architecture REST - Creating APIs - Part 02

Monday, May 16, 2011



In this post, we continue talking about the REST architecture and our progress to create our first API.  This is the second part of the series, if you want to see the Introduction, please check this link

The SOA Principles

The REST is also considered a Service-Oriented Architecture (SOA) , so it the SOA principles must be considered. The REST architecture follows the interoperability by providing support for several types of response. It is a good practice to make your resource accept HTML, JSON or XML in the same method, turning it more portable.  Depending of the target of your application, the number of clients of your services can be bigger in this way. However, providing all those types of response consumes time, and you have to analyze if you are available for working on this interoperability.

It is also important that your RESTful services don't take overloaded operations. This includes heavy processing tasks such as data transformations (XML to JSON, XML to Text/Plain, etc.) as also the validation of the data before each transformation.  This results in the other principle of SOA the weak coupling, that is, make your system less dependent of other modules in order to reduce the modification effects and failure tailoring.  Generally the simple RESTful services systems are divided in the following packages:

  • resources -  The resources of your system which implement the HTTP methods POST, GET, PUT, DELETE. For each request received, it uses the modules of the utils package and the communication provided with dao, if necessary. The resources also have the task of interpret the result , possible failures and response to the client.
  • utils - The utility classes as also related to data transformation.
  • dao -  The classes with the pattern DAO (Data Access Object), responsible for the database transactions
It is also common to see the developers abuse of the methods POST and GET.  Using REST, the developer must know well the four main methods: POST, GET, PUT and DELETE.  We will explain in the next paragraphs about those and comment a little about the HEAD and OPTIONS. For illustrate the explanation, we will use a resource user implemented at http://www.example.com/resources/user/.



POST

Submit the data to be processed at a target resource, which can result in the creation of a new or an update of the existing resources. The data are included in the body of the request. For instance, making a request POST to http://www.example.com/resources/user/  and including the body represented by the JSON in the Figure 01, we will requesting to the server to add this new user. If the user was created successfully, the response will be with a status code 201, pointing that our resource was created.

Figure 1 - JSON as body

GET

Used to request a new representation of the resource specified. In practice, making a request GET in http://www.example.com/resources/user/10 will return as response the user whose the id is 10.  In the other hand if our request was to the url http://www.example.com/resources/user/ , we would have as response the list of all users.

PUT

]It updates the representation of the resource. The data must be sent in the body of the request. Besides, if the URI of the request doesn't not point out to a existing resource, it is allowed to create a new resource with this URI. In our example, if we wanted to update the password of the user with the login "marcelcaraciolo", we just need to make a PUT request to http://www.example.com/resources/user/10 putting the JSON body represented in the next figure, containing the refreshed data.

Figure 2 - JSON as body

DELETE

It deletes a specified resource. It doesn't have the body. If we request the DELETE method to URI http://www.example.com/resources/user/10 it would mean to the serve that we want it to delete the user with the id is equal to 10.

HEAD

Similar to the method GET, but without the body of the response. This method can be used to obtain the metadata of a entity target of the request, without transfer all the data (the body itself of the entity) to the client.

OPTIONS

Return the HTTP methods that the server supports for a specified URI. It can be used to check the features available of a web service. Making a request OPTIONS to http://www.example.com/resources/user/ , we would receive the attribute 'Allow' in the headers with the fields OPTIONS and POST. However making the request OPTIONS to the URI http://www.example.com/resources/user/* ,  we would receive the response OPTIONS, GET, PUT, DELETE and HEAD.  But wait, you may be asking yourself , where is the POST ? Is it missing ?  When you put the wildcat  (*) it is expected some response, but our method POST, using the good practices, is not mapped to accept requests with the URI finishing in 'user/*'.  In other words,  it doesn't make sense to request a POST to 'user/10' , since the id of the resource must be created by the serve. Besides that, in a OPTIONS request, in the body it will come the WADL file, which we will discuss later.

It is important to API developers to know that the client of the service represents the user. So, it is a convention to not use the methods GET and HEAD to do actions,  except the action of information recovering, therefore they are considered safe methods.

Although, knowing that the methods GET and HEAD are secure, the user are conscious about the fact that an action possibly insecure will be requested if it uses the other HTTP methods. To sum up, don't use GET and HEAD to make requests that generate collateral effects. So use the GET method to modify an entity is an anti-pattern and not a good practice in developing REST APIs.

Another important property is the idempotence. PUT, DELETE and OPTIONS are idempotent methods, that is, multiple operations must always return the same result and have the same effect in the application as  one. For instance, making several GET requests to the same URI, it will always return the same response, in case of the requested data didn't change in the interval between the requests.  Finally, the safe methods are indempotent, since it doest not present collateral effects.



HTTP Status Codes

The HTTP Status Codes were created to allow the developers to describe precisely for the clients what happened at the server or even have control of the services. For that, the more specified the response, better. 

The Status Codes has those meanings:

  • 1.xx -  Information
  • 2.xx - Success
  • 3.xx -  Redirect
  • 4.xx -  Client Error
  • 5.xx - Server Error
It is important to developers to know how to response properly with your services. Typically, the responses used by the REST services are 200, 404 or 500, but it is important to understand better the responses of other RESTful services that your application are consuming.  We will see some statuses  codes as follows.

200 - OK
The status code 200 represents that the request was successful. The response returned depends on the method used in the request. If the GET method is used, it will returned the entity corresponding to the requested resource.  In case of POST method, the headers will correspond to the requested resources. Finally if the method was HEAD, it will be returned the headers fields that correspond to the requested resources either.

201 - Created
The request was accomplished and the location of the resource created is returned by the field 'Location' in the response headers. The server must create the resource before return the status code 201. If the resource can't be created immediately, the server must response with 202 (Approved) instead.

202 - Accepted

The request was approved, but it doesn't mean that was finalized. Your purpose is to allow the server to accept asynchronous requests.  Depending on the scenario, it is interesting to include to the body of the response the current status of the request and a path to a state monitor or a time estimative to the request be accomplished.


204 - No Content
The server accomplished the request  successfully but it does not need to response any entity in the body.  Optionally, it may include new or updated meta-information about the the entities in the headers. The response 204 must not have the body. Generally it is the status code response to a DELETE request.

304 - No Modified
If the client has requested with a conditional GET method, but  the documents or the requested data weren't modified, the server must response with this status code. The response 304 must not have a body.

400 -  Invalid Request
Invalid Syntax in the request.

401 -  Not Authorized
The request requires authentication or the user has been refused by the credentials provided.

404 -  Not Found
The server didn't find the resources that correspond to the URI of the request. Generally this response comes as result of a GET request.

409 -  Conflict
There was a conflict in the request with the current state of the resource. This code is only allowed in situations where it expects that the user is able to solve the the conflict and re-send again the request.  For that, the body of the response must include an error message. Generally this scenario occurs in responses to PUT requests.

500 - Internal Server Error
The server came into a unexpected condition that stopped it of finishing the request. For instance, if a problem occurred with the database connection, the response must have the status code 500.


The table below provided gives you a resume of the most used http statuses codes when you are developing your RESTful services.  Please read carefully and know how to use it correctly in order to help the developers that will build applications that will consume your services and know how to handle properly the responses of your API.

HTTP protocol version 1.1 Server Response Codes

In the next post about the REST Services I will present a new service that I am developing using the concepts explained in this series of posts.  It will be related to Location + Question and Answers + Mobile + Python with real code of course! 

I hope you enjoyed,

Marcel Caraciolo

References

[2] http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

58 comments:

  1. Welcome to Wiztech Automation - Embedded System Training in Chennai. We have knowledgeable Team for Embedded Courses handling and we also are after Job Placements offer provide once your Successful Completion of Course. We are Providing on Microcontrollers such as 8051, PIC, AVR, ARM7, ARM9, ARM11 and RTOS. Free Accommodation, Individual Focus, Best Lab facilities, 100% Practical Training and Job opportunities.

    Embedded System Training in chennai
    Embedded System Training Institute in chennai
    Embedded Training in chennai
    Embedded Course in chennai
    Best Embedded System Training in chennai
    Best Embedded System Training Institute in chennai
    Best Embedded System Training Institutes in chennai
    Embedded Training Institute in chennai
    Embedded System Course in chennai
    Best Embedded System Training in chennai

    ReplyDelete
  2. WIZTECH Automation, Anna Nagar, Chennai, has earned reputation offering the best automation training in Chennai in the field of industrial automation. Flexible timings, hands-on-experience, 100% practical. The candidates are given enhanced job oriented practical training in all major brands of PLCs (AB, Keyence, ABB, GE-FANUC, OMRON, DELTA, SIEMENS, MITSUBISHI, SCHNEIDER, and MESSUNG)

    PLC training in chennai
    Automation training in chennai
    Best plc training in chennai
    PLC SCADA training in chennai
    Process automation training in chennai
    Final year eee projects in chennai
    VLSI training in chennai

    ReplyDelete
  3. Embedded system training: Wiztech Automation Provides Excellent training in embedded system training in Chennai - IEEE Projects - Mechanical projects in Chennai. Wiztech provide 100% practical training, Individual focus, Free Accommodation, Placement for top companies. The study also includes standard microcontrollers such as Intel 8051, PIC, AVR, ARM, ARMCotex, Arduino, etc.

    Embedded system training in chennai
    Embedded Course training in chennai
    Matlab training in chennai
    Android training in chennai
    LabVIEW training in chennai
    Robotics training in chennai
    Oracle training in chennai
    Final year projects in chennai
    Mechanical projects in chennai
    ece projects in chennai

    ReplyDelete
  4. Really interesting content which is unique which provided me the required information.
    Dot Net Training in Chennai | .Net training in Chennai | FITA Training | FITA Velachery .

    ReplyDelete
  5. I really enjoyed while reading your article about creating rest architecture, the information you have delivered in this post was damn good. Keep sharing your post with efficient news.
    Regards,
    FITA Chennai complaints|Python Training in Chennai|SAS Training in Chennai

    ReplyDelete
  6. Excellent post!!!. The strategy you have posted on this technology helped me to get into the next level and had lot of information in it.
    salesforce training in chennai | salesforce training institute in chennai

    ReplyDelete
  7. Thanks Admin for sharing such a useful post, I hope it’s useful to many individuals for whose looking this precious information to developing their skill.
    Regards,

    Salesforce Training in Chennai|Salesforce Training|Salesforce Training institutes in Chennai

    ReplyDelete
  8. Great Work. This post is worth everyone’s attention. web design company in chennai

    ReplyDelete
  9. Informative article, just what I was looking for.seo services chennai

    ReplyDelete
  10. This is excellent information. It is amazing and wonderful to visit your site.Thanks for sharing this information,this is useful to me...
    Android training in chennai
    Ios training in chennai

    ReplyDelete
  11. Excellent and very cool idea and the subject at the top of magnificence and I am happy to this post..Interesting post! Thanks for writing it.What's wrong with this kind of post exactly? It follows your previous guideline for post length as well as clarity.
    Embedded Training in Chennai

    ReplyDelete
  12. It is amazing and wonderful to visit your site.Thanks for sharing this information,this is useful to me...
    Android Training in Chennai
    Ios Training in Chennai

    ReplyDelete
  13. Can truly relate and retain this outstanding post. Very well written. web design company Chennai

    ReplyDelete
  14. Good-Looking article! I found some beneficial information in your blog, it was excellent to read, thanks for receiving this great satisfied to my vision, keep sharing.I’ll learn much new stuff right here! Good luck for the next post buddy.
    Dot Net Training in Chennai

    ReplyDelete
  15. Summer training on PLC, SCADA, Automation, Instrumentation in Delhi NCR starting from every Monday and Thursday in this month. Come and Join us to learn Practical tools & techniques with job opportunities...! For Registration Contact +91-9310096831

    ReplyDelete
  16. Candid institute Spring and Hibernate course provides a comprehensive introduction to Spring and Hibernate open source frameworks as well as Web Services and AJAX. Suitable for both Spring3/Hibernate3 and Spring4/Hibernate4, the course includes coverage of the core Spring and Hibernate capabilities, as well as the integration capabilities provided by Spring.
    Spring boot training

    ReplyDelete
  17. The Spring Framework is a lightweight framework for developing Java enterprise applications. It provides high performing, easily testable and reusable code. Spring handles the infrastructure as the underlying framework so that you can focus on your application.Spring is modular in design, thereby making creation, handling and linking of individual components so much easier. Spring implements Model View Container(MVC) design pattern.
    spring mvc validation example

    ReplyDelete
  18. #DIAC providing PLC SCADA Training with 100% Job assurance and FREE DEMO classes on #PLC # SCADA #HMI #Automation #AutoCAD #Instrumentation #Panel Design by Industry Experts. Don't Just Think....!! Call Now 9310096830/931OO96831 ...!!

    ReplyDelete
  19. #DIAC providing PLC SCADA Training with 100% Job assurance and FREE DEMO classes on #PLC # SCADA #HMI #Automation #AutoCAD #Instrumentation #Panel Design by Industry Experts. Don't Just Think....!! Call Now 9310096830/931OO96831 ...!!

    ReplyDelete
  20. It’s always good to learn tips like you share for blog posting. I just started posting comments for blog and facing problem of lots of rejections. I think your suggestion would be helpful for me. I will let you know if its work for me too. Thanks and keep post such a informative blogs.This is an awesome post.Really very informative and creative contents. These concept is a good way to enhance the knowledge.I like it and help me to development very well.Thank you for this brief explanation and very nice information.Well, got a good knowledge.

    AngularJS Training Institute in Chennai
    AngularJS Cetification Training in Chennai
    AWS Training in Chennai
    AWS Devops Training in Chennai
    Best AngularJS Training in Chennai
    AngularJS Training in Chennai

    ReplyDelete
  21. Dot Net framework provides benefits for different kinds of issues include security, exceptional handling, memory management etc., as you said Dot Net helps developer in various ways to deliver an application effectively.
    Regards:
    DOT NET Course Chennai | DOT NET Training Institute in Chennai

    ReplyDelete
  22. Excellent content on Google algorithm updates. Gain more information than expected. I can say your blog is the best I have never seen before about the Google algorithm updates. Thank you admin.
    Regards:
    Digital Marketing Training in Chennai
    Digital Marketing Chennai

    ReplyDelete
  23. SCADA training provides a thorough technical overview of SCADA software used for supervision and data management involved in the industrial automation systems. Call us 9310096831.

    ReplyDelete
  24. We provide PLC, SCADA, AC Drives, HMI, Training in Delhi NCR with 100% placements assistance for all candidates who perform well in the course. Well recognized certificate will be issued for course completed candidates. The training program is specially designed for the students and professionals to gain practical working experience. Call @9310096831.

    ReplyDelete
  25. Thank you a lot for providing individuals with a very spectacular possibility to read critical reviews from this site.
    Best Hadoop Training Institute In chennai

    ReplyDelete
  26. I have found many useful information and news about this topic. Well, Good Job and keep it up.
    Best Android Training in Chennai
    android courses in chennai

    ReplyDelete
  27. Industrial Automation Training - Looking for PLC SCADA Training in Delhi NCR? We have Lab facility fully practically and also giving project training , advanced training with 100% placement support. Call-9310096831.

    ReplyDelete
  28. Your very own commitment to getting the message throughout came to be rather powerful and have consistently enabled employees just like me to arrive at their desired goals.


    Best Java Training Institute Chennai

    ReplyDelete
  29. I have read your blog and i got a very useful and knowledgeable information from your post.Keep sharing your post with efficient news.

    PLC SCADA Training
    plc courses



    ReplyDelete
  30. I believe there are many more pleasurable opportunities ahead for individuals that looked at your site.

    Hadoop Training in Bangalore

    ReplyDelete

  31. Really very informative and creative contents. This concept is a good way to enhance the knowledge.
    thanks for sharing. please keep it up.
    Struts Training in Gurgaon

    ReplyDelete
  32. Your good knowledge and kindness in playing with all the pieces were very useful. I don’t know what I would have done if I had not encountered such a step like this.
    Hadoop Training Institute In chennai

    ReplyDelete
  33. I and my friends were going through the nice, helpful tips from the blog then the sudden came up with an awful suspicion I never expressed respect to the website owner for those secrets.
    amazon-web-services-training-in-bangalore

    ReplyDelete
  34. I feel really happy to have seen your webpage and look forward to so many more entertaining times reading here. Thanks once more for all the details.
    datascience training in chennai

    ReplyDelete
  35. HADOOP TRAINING INSTITUTE IN NOIDA

    CIITN provides Big data hadoop training in Noida in Noida as per the current industry standards. Our training programs will enable professionals to secure placements in MNCs. CIITN is one of the most recommended Hadoop Training Institute in Noida that offers hands on practical knowledge/practical implementation on live projects and will ensure the job with the help of advance level Hadoop Training Courses. At CIITN Hadoop Training in Noida is conducted by specialist working certified corporate professionals having 8+ years of experience in implementing real-time Hadoop projects.CIITN is the best Hadoop training center in Noida with a very high level infrastructure and laboratory facility. The most attractive thing is that candidates can opt multiple IT training course at Noida location. We feel proud by announce that CIITN prepares thousands of candidates for Hadoop training at sensible fees structure which is sufficient for best Hadoop training in Noida to attend the Hadoop classes.Hadoop training course includes “Knowledge by Experiments” strategy to get Hadoop training and performing real-time practices and real-time modulation. This extra ordinary practices with live environment experience in Hadoop Training certifies that you are ready to apply your Hadoop knowledge in big corporations after the Hadoop training in Noida completed.


    Big data hadoop training in Noida

    B-12, Sector - 2, Noida, U.P
    State - Uttar Pradesh U.P
    Country - India
    Pin Code - 201301

    Phone - +917290926565
    Mon - Sun: 10am - 6pm

    ReplyDelete
  36. I ‘d mention that most of us visitors are endowed to exist in a fabulous place with very many wonderful individuals with very helpful things.
    Best Python training Institute in chennai

    ReplyDelete
  37. Best SAP SD Institute In Noida

    SAP SD training in Noida provided by CIITN Noida. We provide IT trainings based on corporates standards that helps students to be prepare for industries. CIITN offers best SAP SD training in Noida,CIITN is one of the best result oriented SAP SD Training Institute in Noida, offers best practically, experimental knowledge in SAP SD training in Noida. SAP SD (Sales and Distribution) is an important module of SAP ERP and handles all the processes of order to delivery.
    It is tightly integrated with other SAP modules like SAP MM & SAP PP. The SAP SD Training module manages customer relationship beginning from raising a quotation to sales order and billing of the product or service. It consists of business processes required in selling, shipping, billing of a product. Key sub-modules of SAP SD are Sales, Customer and Vendor Master Data, Billing, Delivery, Pricing and Credit Management.At CIITN SAP SD training is conducted by 6+ years of experience in managing real-time projects.

    SAP SD Training Institute In Noida
    SAP SD Course In Noida

    ReplyDelete
  38. Best Summer Internship In Noida

    These technologies prepare individuals for fields like software programming, technical support, graphic design, software testing, business analytics. Embedded Systems, Industrial Automation Training and more. Candidates go through a series of comprehensive practical sessions where they work on live problems and implement solutions on real-time basis.
    It has a dedicated placement cell which provides 100% placement assistance to students. The benefits that a student gets out of summer training are innumerable. CIITN,Best Summer training Center for B.Tech/CS/CSE/IT/ BCA/MCA/ B.E /M.tech / B.sc/ M.sc/ Engineering Student has already accomplished itself successfully in the field of Training and Development after setting milestones and bringing smiles to the faces of more than 1 Lakh students. CIITN was incorporated in the year 2002 and over the years CIITN has grown remarkably into the greatest training giant of Northern India.
    There is no looking back to technology! Those passionate for it need not worry about the professional prospects it offers. Courses and trainings in the field of Computer Science and Applications open a wide array of choices for individuals. All you need to do it prepare yourself right!

    Summer Internship Course In Noida

    Summer Internship Training In Noida

    ReplyDelete
  39. java coaching institute in noida
    CIITN provides Best java training in noida based on current industry standards that helps attendees to secure placements in their dream jobs at MNCs.The curriculum of our Java training institute in Noida is designed in a way to make sure that our students are not just able to understand the important concepts of the programming language but are also able to apply the knowledge in a practical way.

    if you are looking for the best oracle sql certification center in Noida, CIIT is worth to consider. CIIT is a oracle training institute offering best sql course, oracle training, sql certification and oracle dba training at affordable price. Best Oracle training in Noida.

    Java Training in Noida
    best java training in noida

    ReplyDelete
  40. Summer Training in PLC SCADA | Automation Training Delhi NCR | Robotics Training
    The major skills for the summer training in PLC automation are based on the instructors and learning environment offered to the students. Affordable Fees and 100% job placement assistance with leading industries. Call @91-9953489987.

    ReplyDelete
  41. Thanks for sharing this good blog.
    Final year project centre is the best source for all engineering students. mini projects in chennai is the best choice for diploma students and mca mini projects in chennai provide the basic project training for the low level projects.

    ReplyDelete
  42. It is amazing and wonderful to visit your site.Thanks for sharing this information!!
    Wedding planners in Coimbatore

    ReplyDelete
  43. DIAC is a leading company who provides training programs and placement for industrial automation, PLC, SCADA, VFD, Control Panels, field instruments, DCS and Servo motor trainings.Our experienced technical team provides practical guidance to our trainees. We help trainees to built their skills to become a skilled programmer. Call@ 9953489987/9310096831.

    ReplyDelete
  44. I believe there are many more pleasurable opportunities ahead for individuals that looked at your site.


    python training in pune

    ReplyDelete
  45. Hello! This is my first visit to your blog! We are a team of volunteers and starting a new initiative in a community in the same niche. Your blog provided us useful information to work on. You have done an outstanding job.
    Best AWS Training in Chennai | Amazon Web Services Training in Chennai

    AWS Training in Bangalore | Amazon Web Services Training in Bangalore

    Amazon Web Services Training in Pune | Best AWS Training in Pune

    ReplyDelete

  46. When I initially commented, I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get several emails with the same comment. Is there any way you can remove people from that service? Thanks.

    AWS Training in Bangalore | Amazon Web Services Training in Bangalore

    Amazon Web Services Training in Pune | Best AWS Training in Pune

    AWS Online Training | Online AWS Certification Course - Gangboard

    ReplyDelete
  47. This information is impressive,I am inspired with your post writing style & how continuously you describe this topic.I feel happy about it and I love learning more about this topic.

    Azure Training
    Azure Training in Chennai

    ReplyDelete