Click here to Skip to main content
Email Password   helpLost your password?

Why publish an n API to the Internet?

Much like a web page, when you make an API public to the Internet, you allow anyone on the planet to use your web method. Once you post an API you should attempt to keep it up and stable. This does not necessarily mean you grantee how long your API will be available. However, if you wish more application programmers to rely on your API then keep it up and stable. Search engines use this sort of technology to encourage people to automate use of their searching services, some AI Chatbot communities use public API for allowing people to create, train and deploy AI chatbots from anywhere to anywhere in the world, Comic book venders use public APIs to allow anonymous business partners to market their comic books. In short, public APIs make anonymous B2B (Business to Business) relationships more feasible. Not all .NET web methods, however, are used for public APIs, for example, some .NET web methods require passwords or use WSSecurity to limit who can use them. Although non-public API's often use .NET web methods, they are outside the scope of this article.

When to use .NET web methods to publish an API to the Internet

Data can be transferred between remote servants using many architectures. Web methods are faster and easier to implement then writing a socket or .NET remoting server. Web methods more self-documenting then ASPX Request/Response. With web methods, you literally mark your method as a web method and let .NET generate the connectivity mechanism and documentation for accessing the method over the Internet. This way you can quickly get your web method up and running and also benefit from the throttles and security of IIS. The web method approach is not ideal if you cannot afford Microsoft server software because IIS in Windows XP Pro, 2000 pro, etc. has been deliberately disabled to prevent it from being used as a web server on the Internet. If windows 2003 Server, 2000 Server, etc. are in your price range then you will benefit from using .NET web methods. You can, however, practice web method development on any of the .NET enabled Microsoft server and workstation operating systems. If you cannot afford a Microsoft server product then focus on exposing your web methods with .NET socket server architectures, which are just as elegant and expandable but not as ideal for rapid development.

Writing web methods

For this article we focus on two different ways to return complex data types from web methods.

Returning complex data types with .NET serialization/de-serialization

This method just initializes a complex data type with some sample data.

   Private Function getDocument() As SComplex
        Dim l_sComplex As SComplex
        l_sComplex = New SComplex()
        l_sComplex.dblVal = 4.14159
        l_sComplex.iVal = 4
        l_sComplex.m_SChildNode.dblChildVal = 4.14159
        l_sComplex.m_SChildNode.iChildVal = 4
        getDocument = l_sComplex
    End Function

This method returns the complex datatype using .NET serialization/de-serialization. You return the object, structure or array is returned and .NET constructs an XML (eXtensible Markup Language) representation.

    <WebMethod()> Public Function complex() As Scomplex
Get sample complex data
        Dim l_sComplex As SComplex
        l_sComplex = getDocument()

Return complex type to be converted into XML in the Response object by .NET

       complex = l_sComplex
    End Function

Returning complex data types with manual document creation

This method manually constructs an xml document and returns it. .NET simply appends the xml in that you manually construct to ""<?xml version�" and returns it in the HTTP (HyperText Transfer Protocol) response.

    <WebMethod()> Public Function complexManual() As System.Xml.XmlDocument

Get sample complex data

        Dim l_sComplex As SComplex
        l_sComplex = getDocument()

Manually construct an XML representation of the sample complex data

        Dim strData As String
        strData = ""
        strData = strData & _
             "<SComplex xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" " & _
            "xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" " & _ 
             "xmlns=""http://tempuri.org/"">"
        strData = strData & "   <dblVal>" & l_sComplex.dblVal & "</dblVal> "
        strData = strData & " <iVal>" & l_sComplex.iVal & "</iVal> "
        strData = strData & " <m_SChildNode>"
        strData = strData & "  <dblChildVal>" & _
            l_sComplex.m_SChildNode.dblChildVal & "</dblChildVal> "
        strData = strData & "  <iChildVal>" & _
            l_sComplex.m_SChildNode.iChildVal & "</iChildVal> "
        strData = strData & " </m_SChildNode>"
        strData = strData & "</SComplex>"
        Dim pDoc As System.Xml.XmlDocument
        pDoc = New System.Xml.XmlDocument()
Return the manually created XML representation of the sample complex data.
        pDoc.LoadXml(strData)
        complexManual = pDoc
    End Function

What is returned

Although written differently, both complex() and complexManual() return the same XML representation of the the sample complex data:

<?xml version="1.0" encoding="utf-8" ?> 
<SComplex xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  xmlns="http://tempuri.org/">
 <dblVal>4.14159</dblVal> 
 <iVal>4</iVal> 
 <m_SChildNode>
  <dblChildVal>4.14159</dblChildVal> 
  <iChildVal>4</iChildVal> 
 </m_SChildNode>
</SComplex>
You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
Generalplanetapi.com does not exist
Parthasarathy Mandayam
11:31 23 Oct '07  
The planetapi.com website that you have referenced does not exist.

Certified VB6, SQL 7 and ASP developer

Generalreturning complex data types
eggertj
6:18 17 Mar '05  
If you are returning a complex data type, can you eliminate the schema information that is generated (as per your example)? Suppose I wanted to return a response that is supported by a DTD. How would I incorporate the DTD (DOCTYPE)?
GeneralThe worst way of dealing with XML
Daniel Cazzulino [MVP XML]
16:30 31 May '04  
Manual creation of XML by means of raw string concatenation is the stone-age approach to XML in .NET.
You have to use XmlTextWriter or programmatic XmlDocument creation. That ensures you have a properly encoded and well-formed document allways.

Daniel Cazzulino
My Weblog Books:
Beg. C# Web Apps ASP.NET Components Toolkit Beg. Web Programming w/VB.NET & VS.NET Pro ASP.NET Server Controls
GeneralTwo ways to return complex data from .NET web methods
Daniel Stephen Rule
20:29 31 May '04  
You’re right, one of the two approaches presented is primitive. Not necessarily the worst but definitely primitive. By the title you can clearly see that the intent is to show two ways to return complex data types from a .net web method. One with automatic serialization and the other by using a lower level (stone-age approach) to construct what .net returns for its web methods. XmlDocument could be used to construct the document but that would not be relevant to the title of this article. However, you bring up a great point that there is an intermediate technology (XmlDocument) which is higher level then constructing a complex data type with string methods but more primitive then using .net serialization.

As for this article it clearly states in the title “Two ways to return complex data from .NET web methods” which does not imply how the complex data types are created but this article describes how to return one manually created vs using serialization. The fact that there are tools that help with creating XML documents is not related to the title of this article. This article simply demonstrates automatic serialization vs. returning manually created complex data types and assumes no DOM/XPath knowledge of the reader.


Chatbot! - Hexbot.com - Natural Language Search Engine Chat Bot
GeneralRe: Two ways to return complex data from .NET web methods
Daniel Cazzulino [MVP XML]
6:18 1 Jun '04  
Well, you could at least have used an StringBuilder that would make for a *just a little* better approach. And you're adding XSD and XSI namespaces to the instance that are not required at all.
There's no intrinsic problem in showcasing your main point, which is NOT creating the doc but returning it, but the thing is that newbies will copy/paste your code and use it in real-world apps. I've seen this happen far too many times.
So, showing them the XmlTextWriter approach at least, which IMO is even easier to structure, is a good thing, and it doesn't add much overhead to the text as it is.
You know, it's like those ASP.NET quick examples showing Response.Write() instead of HtmlTextWriter, HtmlTextWriterTag and HtmlTextWriterStyle. You'd be surprised at how many ASP.NET developers completely ignore their existence.

Daniel Cazzulino
My Weblog
Books:
Beg. C# Web Apps ASP.NET Components Toolkit Beg. Web Programming w/VB.NET & VS.NET Pro ASP.NET Server Controls
GeneralRe: Two ways to return complex data from .NET web methods
Anonymous
8:41 1 Jun '04  
Good observation StringBuilder could make this web method return faster if it did not meet some timing requirement and more speed was needed.

StringBuilder would be an optimization but is unrelated to what is being explained in this article. That would be better for an article on optimizing string operations. I assume “real-world app” refers to capitalist driven software -- if so, maybe a lot of coders don't optimize when it is not necessary to meet their timing requirements and pay their bills. One can't optimize code without timing requirements or they risk coding unnecessary optimization. The reason a lot of coding books and articles fail is because they are not practical and show too much unrelated material in each example. It is not productive to be dogmatic about coding rather look at all code in perspective of what is intended to do.
GeneralRe: Two ways to return complex data from .NET web methods
Daniel Stephen Rule
8:46 1 Jun '04  
Good observation StringBuilder could make this web method return faster if it did not meet some timing requirement and more speed was needed.

StringBuilder would be an optimization but is unrelated to what is being explained in this article. That would be better for an article on optimizing string operations. I assume “real-world app” refers to capitalist driven software -- if so, maybe a lot of coders don't optimize when it is not necessary to meet their timing requirements and pay their bills. One can't optimize code without timing requirements or they risk coding unnecessary optimization. The reason a lot of coding books and articles fail is because they are not practical and show too much unrelated material in each example. It is not productive to be dogmatic about coding rather look at all code in perspective of what is intended to do.

Chatbot! - Hexbot.com - Natural Language Search Engine Chat Bot
GeneralRe: Two ways to return complex data from .NET web methods
Daniel Cazzulino [MVP XML]
9:52 1 Jun '04  
"Capitalist driven software", "risk coding unnecessary optimization", oh boy. I think you completely misunderstood me.
It's not about capitalism or requirements timing, it's about doing the things with the appropriate API for the job. Every .NET developer should know that contatenating more than about 10 strings readily justifies switching to the StringBuilder. It's just good programming practice.
You don't need to measure any requirements or be a capitalist monk to know that you don't have to do certain things, i.e. load a huge XML document just to retrieve a couple nodes. It's common sense and good programming practice, that's all.
Want a very concrete example? Mark Fussel (System.Xml PM) discusses the usage of XmlNameTable (http://blogs.msdn.com/mfussell/archive/2004/04/28/121854.aspx). And do you know why he has to do so? Because it's not used in most MSDN documentation, as it's not the primary point being shown, just like your case. The consequence? Most .NET developers completely ignore what's it all about. They are losing about 10% performance straight out of ignorance. Everybody just assumed that the code spread everywhere *not* using the XmlNameTable (because it was showing an XmlTextReader, an XmlDocument, etc.) was the right way to do things.
We should all learn from that. Dogmatic or not, what we write is read and applied (hopefully) by other developers that might not know there are better ways.

The moral: always show the better approach to any problem, even if it's a short example. It's far better to point the reader to further articles explaining what you've ocasionally used but is not the main target of your example.

Daniel Cazzulino
My Weblog
Books:
Beg. C# Web Apps ASP.NET Components Toolkit Beg. Web Programming w/VB.NET & VS.NET Pro ASP.NET Server Controls
GeneralRe: Two ways to return complex data from .NET web methods
Daniel Stephen Rule
10:48 1 Jun '04  
"It's far better to point the reader to further articles explaining what you've occasionally used but is not the main target of your example."

I think we both know that that is far to general to be true for all cases. In some cases there are articles that include unnecessary technologies, which make the article incomprehensible to the audience that the article was written for. Perhaps in this case introducing a StringBuilder would not have detracted too much from the clarity of the article's purpose.

As far as coding styles, there are little or no "common sense" coding standards that work for all cases and should be dogmatically followed. In fact, the more open minded a computer programmer the less limited they are and more dynamic and creative their solutions. Not just in maintainability or optimization, but in time-to-deliver and ability to minimize learning overhead.


Chatbot! - Hexbot.com - Natural Language Search Engine Chat Bot
GeneralRe: Two ways to return complex data from .NET web methods
Anonymous
8:43 1 Jun '04  
.
GeneralProblem with passing complex types
Meera Rajaram
6:12 26 May '04  
I am building a Web Service which should accept sqlcommand parameters, and the database name. This web service will connect to the database, Run the query and return the results. The first problem I faced was that WebServices cannot accept SQLCommand object as an input parameter(since it is not XML Serializable). I tried to overcome this problem by defining my class which would accept the properties that we set for a parameter(like Name, size, direction, type,etc)

For example I have a class
Public class prmParameter
Public strParameterName as string
Public strParameterType as SQlDbType
etc...
Public Sub New()
some initializations...
end sub
Public Sub New(ParameterName as string, ParameterType as SQLDBType)
strParameterName=ParameterName
strParameterType =ParameterType
end sub
End Class

I have created the class in a separate class library and included its reference in my Web Service.

IN my webservice I then expose a method which takes an array of prmParameter(since we can have multiple parameters passed to a stored procedure), StoredProcedure or Query name, CommandType(StoredProcedure, Text, TableDirect),DBName.

The signature of my method would look like this:
Public Function ExecuteProc(aryParams() as prmParameter, strQuery as string, cmdType as CommandType,strDBName as string) as DataSet


The problem that I am facing is that the overloaded constructor does not get exposed at the client end. So for each parameter to be passed, I have to create an instance of prmParameter and individually set its properties. Though this runs fine, it is a very cumbersome process.

Is there any way to avoid this? I had tried creating another class which has an array of parameters. I had put in a method in that class for accepting a SQLcommand object and building the PrmParameter array using the SQLCommand Object. But once again, the method did not get exposed at the client end Cry

Please help!


Generalthanks
Anonymous
9:26 7 May '04  
just what i needed
GeneralThanks for sharing!
Anonymous
11:33 20 Apr '04  
thx! Smile
GeneralI needed this thanks!
Anonymous
11:33 20 Apr '04  
This is perfect. It's cool how .net converts data structures into xml for us.
GeneralHelp with site
dog_spawn
6:25 10 Apr '04  
Hi. I read your most recent article and decided to check out some of your other work. This is quite interesting but when I went to the site http://www.planetapi.com/[^] I couldn't get anything to work. What is happening? Any tips?
GeneralNice work.
Jason L. Tormlage
16:43 8 Mar '04  
Nice work. BTW, Planet API is very cool. I have been using Planet API since I got into hobby .net coding.
GeneralWhy publish API's
Mark Focas
13:52 8 Mar '04  

If you are going to publish an API to the public, I assume there is a motivation, so surely it should be well thought out, well planned, and thoroughly tested. I disagree with your lines:

This does not necessarily mean you grantee 
how long your API will be available or how well it will work, just that
you have chosen to make it public at the moment.
If this is what someone is seriously thinking, then they shouldn't publish their API's to the public, they will just waste peoples times, and it won't really give them much credence in the eyes of more serious developers

Being in a minority of one, doesn't make you insane
George Orwell
However, in my case it does

GeneralRe: Why publish API's
Anonymous
16:34 8 Mar '04  
I agree with the author. You should not rely on any one a public api. Find more then one and have a backup. Do not count on any single public API to stay up. Its good coding practice.
GeneralRe: Why publish API's
andy brummer
19:50 8 Mar '04  
Better yet, contact the person or company responsible for the service and make some kind of "agreement" with them. Smile

-Andy Brummer
GeneralRe: Why publish API's
Anonymous
7:41 9 Mar '04  
If you have time to fiddle around with that. I agree. For AI chatbots, its best to just use as many as will help your chatbot be smarter and just not rely on any one to be up at any given time. Going forward, the less humans have to interact and the more organizations can just publish B2B relationships to the world the better. E.g. you don't call codeproject.com before using their website. You just use it. So they established a relationship w/ you w/o you talking to them necessarily. That is more efficient then if you had to call every web page you ever visited before talking to them. The same goes for web methods in AI chatbot projects.


Last Updated 8 Mar 2004 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010