1 / 110

فصل دو: Web API و Web Service

فصل دو: Web API و Web Service. دوره SOA استانداری قم - جواد تقی زاده. Web Service یا Web API. روشی برای ارتباط بین ابزارهای الکترونیکی در اینترنت می باشد A Web service  is a method of communication between two electronic devices over the World Wide Web

tahlia
Télécharger la présentation

فصل دو: Web API و Web Service

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. فصل دو: Web API و Web Service دوره SOA استانداری قم -جواد تقی زاده

  2. Web Service یا Web API • روشی برای ارتباط بین ابزارهای الکترونیکی در اینترنت می باشد • AWeb service is a method of communication between two electronic devices over the World Wide Web • In other words, a web service helps to convert your application into a web-based application.

  3. نمونه Web API یا سرویس وب • سایت جستجوی www.faroo.com • لزوم داشتن API Key • JSON • http://www.faroo.com/api?q=iphone&start=1&length=10&l=en&src=web&f=json • JSON-P • http://www.faroo.com/api?q=iphone&start=1&length=10&l=en&src=web&f=json&jsoncallback=mycallback • XML • http://www.faroo.com/api?q=iphone&start=1&length=10&l=en&src=web&f=xml • RSS • http://www.faroo.com/api?q=iphone&start=1&length=10&l=en&src=web&f=rss

  4. نمونه موتورهای جستجوهای Web API یا وب سرویس • Web Service Search Engine: • http://www.programmableweb.com • http://seekda.com

  5. Seekda.Com Shutdown

  6. Programmableweb.Com • API News • API Directory • Mashup • جستجو در API

  7. Programmableweb.Com • نگهداری API های مدل مختلف: • AIM (OSCAR) • Atom • Blogger • DTC-XML • GData • GData • hCalendar • iCal • JavaScript • JSON-RPC • REST • RSS • SMS • SOAP • XML-RPC • XMP

  8. Web Service markup languages • There are a number of web services that use markup languages: • JSON-RPC • JSON-WSP • Web template • Web Services Description Language (WSDL) from the W3C • XML Interface for Network Services (XINS) provides a POX-style Web service specification format • Web Services Conversation Language (WSCL) • Web Services Flow Language (WSFL) (superseded by BPEL) • WS-MetadataExchange • Representational state transfer (REST) versus remote procedure call (RPC) • XML-RPC - XML Remote Procedure Call

  9. Web APIsرشد • Significant growth of Web APIs • > 5,400 Web APIs on ProgrammableWeb (including SOAP and REST APIs) [end of 2009: ca. 1,500 Web APIs] • > 6,500 Mashups on ProgrammableWeb(combining Web APIs from one or more sources) • SOAP services are only a small part of the overall available public services

  10. تاریخچهWeb services Web Services have evolved through three distinct Phases.

  11. Stubs چیست؟ • A stub is a small program routine that substitutes for a longer program, possibly to be loaded later or that is located remotely. • The stub accepts the request and then forwards it (through another program) to the remote procedure. • When that procedure has completed its service, it returns the results or other status to the stub which passes it back to the program that made the request.

  12. انواع پروتکل وب سرویس Semantic Web Services

  13. مقایسه CORBA با وب سرویسها • Corbaشی محور است در حالیکه وب سرویس پیام محور • Corba اتصال قوی است در حالیکه وب سرویس ها اتصال ضعیف هستند • در Corba محتوای باینری CDR منتقل می شود در حالیکه در وب سرویس XML منتقل می شود • Corba دارای State است ولی وب سرویس بدون State است • مخزن سرویس در Corba، Corba Naming Service است در وب سرویس UDDI است

  14. XML-RPC

  15. XML-RPC چیست؟ XML-RPC is a remote procedure call protocol using XML as data format and HTTP as transport protocol.

  16. معماری XML-RPC

  17. XML-RPC Where to use XML-RPC  XML-RPC may be suited for simple applications or situations where clients implemented in different technologies need to interact with a server with simple read-write operations where a more complex middleware technology would be overkill.  XML-RPC is a solution to integrate different platforms with a simple middleware.  XML-RPC is very simple so it can be implemented also for platforms without open source or commercially available XML-RPC libraries

  18. XML-RPC Data Types

  19. XML-RPC نحوه فراخوانی متد و دریافت پاسخ XML-RPC Request <?xml version="1.0"?> <methodCall> <methodName>examples.getStateName</methodName> <params> <param> <value><i4>40</i4></value> </param> </params> </methodCall> XML-RPC Response <?xml version="1.0"?> <methodResponse> <params> <param> <value><string>South Dakota</string></value> </param> </params> </methodResponse> XML-RPC Fault <?xml version="1.0"?> <methodResponse> <fault> <value> <struct> <member> <name>faultCode</name> <value><int>4</int></value> </member> <member> <name>faultString</name> <value><string>Too many parameters.</string></value> </member> </struct> </value> </fault> </methodResponse>

  20. پیاده سازی XML-RPC Python xmlrpclib Renamed xmlrpc.client in Python 3. C++ Libiqxmlrpc Ultra lightweight XML-RPC library for C++ XML-RPC for C and C++ XmlRpc++ XmlRpc C++ client for Windows gSOAP toolkit for C and C++ supporting XML-RPC and more libmaia: XML-RPC for Qt/C++ XML-RPC Client S60: XML-RPC for Symbian/C++ Objective-C / GNUstep / Cocoa XMLRPC Framework Erlang XML-RPC for Erlang http://www.xmlrpc.org/

  21. پیاده سازی XML-RPC Groovy XML-RPC Module Java Apache XML-RPC: Open source library for Java XML-RPC Delight Redstone XML-RPC Library: Redstone's Open Source Library – XML-RPC implementation in Java XML-RPC Library for Java ME: Open source client-side library for Java ME aXMLRPC: Open source XML-RPC client library for Java and Android JavaScript XML-RPC for Node.js: Open source JavaScript XML-RPC client and server for node.js Mimic XML-RPC: Open source JavaScript XML-RPC client cross-browser. XMPP pyJabberXMLRPC: Python classes for XMPP Jabber-RPC: Over the Extensible Messaging and Presence Protocolprotocol

  22. پیاده سازی XML-RPC PHP XmlRpc in Zend_Framework 2.2: XmlRpc Server and Client in Zend_Framework 2 Perl RPC::XML: A set of Perl classes for core data, message and XML handling Frontier::RPC: Another set of Perl modules for XML-RPC client/server implementation XML::Compile::RPC: RPC extension to XML::Compile Other JSON/XML-RPC Client and Server: Abstract away the differences between JSON-RPC and XML-RPC RemObjects SDK Delphi and .NET package for XML-RPC, in addition to SOAP and others RealThinClient SDK: For Delphi/C++ XML-RPC for ActionScript: For Flash ActionScript 2.0 as3-rpclib: For Flex/Actionscript 3 XML-RPC.NET: Open source library for .NET clients and servers XmlRpc-Light: Client and server library for OCaml S-XML-RPC: Client and server library for Common Lisp clj-xmlrpc: XML-RPC client for Clojure necessary-evil: XML-RPC Client and Ring-based Server for Clojure HaXR: Client and server library for Haskell Ruby XML-RPC library: For Ruby XML-RPC interface to Lua: For Lua android-xmlrpc: A light XML-RPC client for Google Android XML-RPC for Tcl: A Tcl implementation of XML-RPC providing client and server support RebXR: a full client/server XML-RPC implementation for REBOL

  23. Asp.net XML-RPC Statename.rem: public class StateNameService : XmlRpcService { [XmlRpcMethod("examples.getStateName", Description="Return name of state given its number")] public string getStateName(intstateNum) { if (stateNum == 41) return "South Dakota"; else return "Don't know"; } } Web.Config <configuration> <system.web> <httpHandlers> <add verb="*" path="statename.rem" type="CookComputing.StateNameService, StateNameService" /> </httpHandlers> </system.web> </configuration> http://localhost/xmlrpc/statename.rem

  24. JSON-RPC

  25. JSON-RPC چیست؟ • روش فراخوانی تابع از راه دور(RPC) است • شباهت زیادی به XML-RPC بالاخص سادگی و قابلیت استفاده در Client ها • ساختار پیام های ارسالی و دریافتی به جای XML مبتنی JSON (Javascript Object Notation) می باشد • پشتیبانی از UTF-8 • سایت رسمی: http://json-rpc.org

  26. JSON نمونه ای از ساختمان داده • { • "firstName": "John", • "lastName": "Smith", • "address": { • "streetAddress": "21 2nd Street", • "city": "New York", • "state": "NY", • "postalCode": 10021 • }, • "phoneNumbers": [ • "212 555-1234", • "646 555-4567" • ] • } Name/Value Pairs Child properties Number data type String Array

  27. JSON Data Types Primitive types: string Sequence of 0..n Unicode characters, enclosed in quotation marks. Example: „hello world“ number Numerical value (represention as used in most programming languages). Examples: 3.45, 5E3 boolean true / false value null Null value (= no object or no value) Structured types: Array Ordered sequence of 0..n values. Example: [1,3,4] Object Unordered collection of 0..n name:value pairs. Name = string Value = string, number, boolean, null, object, array. Example: {"jsonrpc": "2.0", "method": "update", "params": [1,2,3,4,5]}

  28. JSON Data Structures

  29. JSON vs. XML

  30. JSON-RPC انواع پیام ها: Request: Method invokation with arguments encoded in JSON. Response: Reply to method invokation containing the return argument encoded in JSON. لزوم استفاده شناسه پیام (requestid) برای پیام های درخواست 3. Notification: Asynchronous request without response. اختیاری بودن برای پیام های اعلان(Notification)

  31. مثال های JSON-RPC • RPC call with parameters: فراخوانی تابع تفاضل با مقدارهای 84 و 42 و شماره پیام 1 • Request:{"jsonrpc": "2.0", "method": "subtract", "params": [84, 42], "id": 1} • Response:{"jsonrpc": "2.0", "result": 42, "id": 1} • RPC call with named parameters: • Request:{"jsonrpc": "2.0", "method": "subtract", "params": {"subtrahend": 42, "minuend": 84}, "id": 3} • Response:{"jsonrpc": "2.0", "result": 42, "id": 3} • Notification: بروز رسانی • Request:{"jsonrpc": "2.0", "method": "update", "params": [1,2,3,4,5]} • RPC call with invalid JSON: • Request:{"jsonrpc": "2.0", "method": "foobar, "params": "bar", "baz] } • Response:3 {"jsonrpc": "2.0", "error": {"code": -12345, "message": "Parse error."}, "id": null}

  32. کاربردهای JSON-RPC 1- مدیریت ابزارها و سخت افزار (Device) بر بستر اینترنت (مناسبتر از پروتکل SNMPیا Simple Network Management Protocol که توسط فایروالها فیلتر می گردد ) 2- امکان Server Push، به علت مبتنی بودن بر جاوااسکریپت و امکان اجرا جاواسکریپت بر روی کلاینت ها امکان بروز کردن وضعیت کلاینت ها وجود دارد Web application where the web server needs to update the client (server push). JSON-RPC, as its name implies, was derived from Javascript. The client side of the application is usually Javascript based (e.g. AJAX).

  33. پیاده سازی JSON-RPC

  34. JSON&Jquery&Asp.netلیست وابسته <%@ WebHandler Language="C#" Class="LoadCities" %> using System; using System.Web; using System.Text; public class LoadCities : IHttpHandler { public void ProcessRequest (HttpContext context) { string StateID = context.Request.QueryString["StateID"]; StringBuilderstrCities = new StringBuilder(); if (StateID == "1") { strCities.Append("["); strCities.Append("{"); strCities.Append("\"City\":\"Chennai\","); strCities.Append("\"ID\":\"1\""); strCities.Append("},"); strCities.Append("{"); strCities.Append("\"City\":\"Coimbatore\","); strCities.Append("\"ID\":\"2\""); strCities.Append("}"); strCities.Append("]"); } context.Response.ContentType= "application/json"; context.Response.ContentEncoding = Encoding.UTF8; context.Response.Write(strCities.ToString()); context.Response.End(); } public boolIsReusable { get { return false; } } } استفاده از HttpHandler <script src="_scripts/jquery-1.2.6.js" type="text/javascript"></script> <script language="javascript"> $(document).ready(function() { $("#ddlStates").change(function() { $("#ddlCities").html(""); varStateID = $("#ddlStates > option[@selected]").attr("value"); if (StateID != 0) { $.getJSON('LoadCities.ashx?StateID=' + StateID, function(cities) { $.each(cities, function() { //$("#ddlCities").append("<option value=" + this['ID'] + ">" + this['City'] + "</option>"); $("#ddlCities").append($("<option></option>").val(this['ID']).html(this['City'])); }); }); } }); }); </script>

  35. using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; using System.Runtime.Serialization.Json; using System.Web.Script.Services; [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [ScriptService] public class WebService : System.Web.Services.WebService { public WebService() { } [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public CityListGetCities() { CityListoBoCityList = new CityList() { new City { Name = "New Delhi", ID = 1 }, new City { Name = "Kanpur", ID = 2 }, new City { Name = "Gurgaon", ID = 3 } }; return oBoCityList; } } public class City { public City() { } public string Name { get; set; } public Int32 ID { get; set; } } public class CityList : List<City> { public CityList() { } } Asp.Net JSON Web Service استفاده از ScriptService <head id="Head1" runat="server"> <script type="text/javascript" src="Scripts/jquery-1.7.1.min.js"></script> <script language="javascript" type="text/javascript"> $.ajax({ type: 'POST', url: 'WebService.asmx/GetCities', data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", error: function (jqXHR, textStatus, errorThrown) { alert(jqXHR.responseText); }, success: function (data) { var cities = data.d; $.each(cities, function (index, cities) { alert("City Name: " + cities.Name + "\nID: " + cities.ID); }); } }); </script> </head>

  36. SOAP Web Service

  37. SOAP • سال 1998 ارائه شد • •SOAP is a communication protocol • •SOAP is for communication between applications • •SOAP is a format for sending messages • •SOAP communicates via Internet • •SOAP is platform independent • •SOAP is language independent • •SOAP is based on XML • •SOAP is simple and extensible • •SOAP allows you to get around firewalls • •SOAP is a W3C recommendation • Using SOAP over HTTP allows for easier communication through proxies and firewalls than previous remote execution technology(but not required!).

  38. نکات دیگر در خصوص Soap • پشتیبانی خوب از SOAP در Sun, Java, .NET and Flex • پشتیبانی ضعیف از SOAP در PHP و Python • جایگزین ها • REST • سایر متدهای RPC مانند XML-RPC و یا تکنولوژی های میان افزار مانند CORBA

  39. سه عنصر کلیدی در وب سرویس استاندارد

  40. سه عنصر کلیدی در وب سرویس استاندارد • SOAP) Simple Object Access Protocol) ساختاري براي تبادل پیامهاي در قالب XML است که بین سرویس هاي وب مبادله می شود • WSDL) Web service Description Language) زبانی مبتنی بر XML جهت توصیف ویژگی هاي عملیاتی سرویس هاي وب استفاده می شود و داراي دو بخش تعریف واسط و پیاده سازي است. • UDDI یاUniversal Description ,Discovery and Integration واسطی است براي انتشار و شناسائی سرویس هاي وب و شامل یک مخزن می شود که ارائه دهندگان به انتشار و تبلیغ سرویس خود می پردازند تا دیگران بتوانند آن را شناسائی کنند.

  41. Web Service Technology Stack • 4 لایه تکنولوژی در وب سرویس(Technology Stack) • لایه پیام رسانی • لایه توصیف و کشف سرویس • لایه کیفیت سرویس • لایه فرایندهای وب سرویس

  42. ساختار سند شرح وب سرویس(Web service description document)

  43. درخت ساختار WSDL 1.1

  44. WSDL: Description& Types <?xml version="1.0" encoding="UTF-8"?> <descriptionxmlns="http://www.w3.org/ns/wsdl" xmlns:tns="http://www.tmsws.com/wsdl20sample" xmlns:whttp="http://schemas.xmlsoap.org/wsdl/http/" xmlns:wsoap="http://schemas.xmlsoap.org/wsdl/soap/" targetNamespace="http://www.tmsws.com/wsdl20sample"> <!-- Abstract type --> <types> <xs:schemaxmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://www.tmsws.com/wsdl20sample" targetNamespace="http://www.example.com/wsdl20sample"> <xs:element name="request"> ... </xs:element> <xs:element name="response"> ... </xs:element> </xs:schema> </types> Type های درخواست و پاسخ برای هر متد تعریف می شود

  45. WSDL: Interfaces <!-- Abstract interfaces --> <interface name="Interface1"> <fault name="Error1" element="tns:response"/> <operation name="Opp1" pattern="http://www.w3.org/ns/wsdl/in-out"> <input messageLabel="In" element="tns:request"/> <output messageLabel="Out" element="tns:response"/> </operation> </interface> متد ها در قسمت Operation تعریف می شود

  46. WSDL:Binding <!-- Concrete Binding Over HTTP --> <binding name="HttpBinding" interface="tns:Interface1" type="http://www.w3.org/ns/wsdl/http"> <operation ref="tns:Get" whttp:method="GET"/> </binding> <!-- Concrete Binding with SOAP--> <binding name="SoapBinding" interface="tns:Interface1" type="http://www.w3.org/ns/wsdl/soap" wsoap:protocol="http://www.w3.org/2003/05/soap/bindings/HTTP/" wsoap:mepDefault="http://www.w3.org/2003/05/soap/mep/request-response"> <operation ref="tns:Get" /> </binding> در این قسمت bindingتعریف می شود شامل تعیین پروتکل انتقا، سبک وب سرویس (RPC/Document)

  47. WSDL: Service Name & EndPoint <service name="Service1" interface="tns:Interface1"> <endpoint name="HttpEndpoint" binding="tns:HttpBinding" address="http://www.example.com/rest/"/> <endpoint name="SoapEndpoint" binding="tns:SoapBinding" address="http://www.example.com/soap/"/> </service> </description> در این قسمت نام سرویس، آدرس سرویس و نحوه اتصال به وب سرویس در قسمت endpoint ها تعریف می شود

More Related