0

Is there a way to check whether a product already exists in Magento using the SOAP API that doesn't require using exception handling for the control flow?

I have the following code that works, but I wouldn't say it follows best practices.

Dim productExists As Boolean
Try
    Dim webService As MagentoService = New MagentoWS.MagentoService
    Dim productInfo As catalogProductReturnEntity = webService.catalogProductInfo(sSessionId, sku, String.Empty, Nothing, "sku")
    productExists = True
Catch ex As SoapHeaderException
    productExists = False
End Try

I have to catch the SoapHeaderException and then use the fact that the exception was thrown to know that the product doesn't exist.

1

I'm not sure how .NETs SOAP API would handle this, but I'd try using the catalog_product.list method with a SKU filter. If the resulting list/array/collection/whatever-its-serialized-as is empty, then you know the product doesn't exist.

Per the comments below, the following code should get you that list

Dim productExists As Boolean 
Dim webService As MagentoService = New MagentoWS.MagentoService 
Dim filters As filters = New filters() 
filters.filter = {New associativeEntity() With {.key = "sku", .value = sku}} 

Dim productInfo As catalogProductEntity() = webService.catalogProductList(sSessionId, filters, String.Empty) 

productExists = productInfo.Count() > 0
5
  • like the idea with the list+filter combination! Nov 18 '13 at 6:55
  • This worked great. Can you add the sample code to your answer, and I will accept it. Dim productExists As Boolean Dim webService As MagentoService = New MagentoWS.MagentoService Dim filters As filters = New filters() filters.filter = {New associativeEntity() With {.key = "sku", .value = sku}} Dim productInfo As catalogProductEntity() = webService.catalogProductList(sSessionId, filters, String.Empty) productExists = True
    – Ryan Gates
    Nov 19 '13 at 16:25
  • @RyanGates Code's up there — it looks like some (the length/emptiness check for productInfo maybe got cut off though?
    – Alan Storm
    Nov 19 '13 at 17:38
  • You're correct, here's the rest: productExists = productInfo.Count() > 0.
    – Ryan Gates
    Nov 19 '13 at 18:24
  • @RyanGates All set! If I missed something try gist for the code snipped and I'll edit things in place gist.github.com
    – Alan Storm
    Nov 19 '13 at 18:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.