I have a database table which stores Incident details. Each Incident can have an image saved for it. There are some Incidents which will not have an image for it.
I have an API which pulls the image for a given Incident. I have an issue with handling the API in case an Incident doesn’t have the image.
What is the best approach to handle this (and why 🙂 )?:
- Telling the client in advance which Incident has the image, and which don’t. So the client calling the API should only call it when there is an image for the Incident.
- Sending a predefined error message as the result.
- Sending a generic placeholder like image to the client when an image is not available for the Incident.
1
I would prefer option 1.
This would involve expanding your current definition of an Incident to contain a hasImage
flag so that the client can decide for which Incidents to call the image fetching API (eg, getIncidentImage(...)
)
Thos covers modelling and API design.
As other people have mentioned, from a UX perspective, you might want to include a placeholder image in the UI when an Incident lack one. If it were up to me, fetching this placeholder image would be done by invoking a getPlaceholderImage()
method in your image API and not the getIncidentImage(...)
method. This is because, in my opinion, the decision to use a placeholder image when an Incident image is missing is a UI concern and, therefore, your image API shouldn’t be aware of it.
Also, as I mentioned in my earlier comment, if it’s perfectly normal for an Incident to not have an associated image then I recommend not returning an error when calling your getIncidentImage(...)
message. An empty result should be sufficient and is less confusing to the API users.
1
It depends on the technology you use. Normally in this case you would return a Type
that describes the possibility of an image. In some languages these types are built in (Option
in Scala, Maybe
in Haskell). In other ones you can write them yourselves or use a library that includes these types. For javascript (which may be what you can use, I guess), you can find a good explaination and implementation here.
In addition you should – as you mentioned – have a method to ask, if an image exists.
I would use option
- Change the API so every request for an image returns the image + a status information. If there is no image, you return a 0 byte stream for the image and a status like “no image available”.
So the user of the API needs only one roundtrip to retrieve the full information, the operation is atomic, you don’t return an error for a valid operation, and you don’t waste bandwidth by sending the same image placeholders over the line over and over again.
If the user of the API wants to display a (fixed) placeholder, he is free to do this, but that should be decoupled from the API itself.
1