335 points · by blopeur · 6y ago · 248 comments
I also once worked with an API where you had to send the data in POST format - abc=123&def=456. After much pressure from their customers, they finally relented and added an XML version of their API... where your request could look like this: <request>abc=123&def=456</request>.
Even better, note the & is not an & - you can't even use a standard XML parser to interpret the result.
Also: APIs that have a mix of strongly and eventually consistent calls and no documentation about which is which. Or, an API that was at one point strongly consistent turns eventually consistent without warning.
When they turned up for a meeting to present the fruits of their labour they got patted on the back by all the managers for a job well done. Record time too!
They faces fell when I told them that I'm flat out rejecting their API design and that they will have to start from the beginning.
Their excuse for the design was that ampersands are too hard to process, so base64 encoding made them "safe" to include in the REST API.
Sometimes you just have to put your foot down about this kind of idiocy.
Still, perhaps not as bad as using XML documents as database keys...
https://stackoverflow.com/questions/21087648/xml-invalid-cha...
I know about this because I received a file with illegal CDATA characters once.
Like, if I'm checking the result of a batch processing job, I want to know if the job finished & resulted in an empty set, or there is simply no result yet.
It's "the thing you're looking for doesn't exist" vs. "the thing you're looking for exists, but is empty."
The API I'm thinking of though was effectively a wrapper around a database query which retrieved items.
That's what gets me about that decision you see. When you get nothing from a database, you get an empty set. The runtime was some version of .NET Framework, which by default would write an empty set as an empty array. So it wasn't even an accident - someone actually had to add extra logic to make it return null.
It is useful in cases such as indicating an operation was successful, but zero rows were affected. Using it as a number resolves to zero, using it as a boolean results in true.
I think in the general sense under API though, a status flag is the best way to avoid confusion as you say. Null could just as easily mean 'error' as 'not yet finished'.
But then the system evolves to not be many-to-one, but many-to-many. To avoid breaking old clients, they make it so the only difference is when they return multiple related records, in which case they're given in an array.
Thus you now have: null for empty, the record it self if there is only one related, and an array of records if there are more than one related.
My point was just that the absence of a value is distinct from an empty value. And that intentionally modeling those 2 cases separately can remove a lot of ambiguity.
There is no justification for NULLs
This just reminded me of a long ago incident at a former employer. I worked in back-office at a hedge fund and was responsible for maintaining several APIs & services written in C++. The APIs were pretty straight forward query for object(s), get back a vector of objects. If nothing was found, you'd get back an empty vector.
The company also had a program where they'd hire grad students right out of school and immerse them in the trading desk, working on trading algorithms and such. One such kid sent in a "bug report" directly to me, CCing all of front office. The "bug"? We was querying for something that didn't exist, so he got back an empty vector. He didn't check that it wasn't empty, and immediately accessed the front of the vector. Boom, segfault.
Normally, I would have been kind to such a junior dev, but their original email was very condescending and went to an unnecessarily large audience - like hundreds of people that didn't have time for this. His email read something to the effect of "Your API is crashing my code. Fix your API."
Instead, this junior got a whole other lesson instead. I replied all, and included all of back-office on the email (so the rest of the team was aware to watch out for this clown). "The API is working perfectly fine and as designed. The fuck up is on your end. You queried for something that doesn't exist and proceeded to dereference and empty vector. Fix YOUR fucking code."
Surely there must have been a better way for you to handle this situation.
Simply being wrong in public deserves a gentle correction (possibly in private, again, depending on the circumstances), but often I don't really care to be nice to people who aren't being nice. It's certainly possible that being nice all the time in situations like this gets you better outcomes overall, but we all have a limited amount of patience to dole out, and some people just don't deserve it sometimes.
And on the other hand, some people don't get the message when you respond politely. Responding politely in this case could just as easily teach the junior that his debugging strategy (blame anyone but himself) and dickish tone were completely ok. There's certainly a polite way to inform the junior that his behavior won't be tolerated, but I can't fault someone for simply responding in kind.
The junior was in the wrong, so I think you'd agree that a correction is in order. Replying-all is one way to do such a correction. The alternative would be to force him to issue a retraction himself.
One child node? That would be one JSON object / value for you sir. Multiple child nodes? That would be on JSON array for you sir. No child node? No JSON type for you sir.
So what happened when the amount of child nodes was dynamic? You would either get: nothing, an object, or an array of objects. Oh the fun times we had!
The first one, ExecuteXML, takes an <XmlBody> representing a regular SAP B1 XML request and passes it on to one of the real SAP services. We have to find our own XSDs for the inner part, because they sure as hell don't have those.
The second one is ExecuteSQL. It lets us run raw SQL against the SAP database. It doesn't have any support for prepared parameters. What it does have is a blacklist to prevent DDL and other funny business, such as semicolons. This blacklist runs on the raw string you send, and doesn't understand any escape characters. To send a string containing a literal semicolon, I had to turn it into CONVERT(VARCHAR(MAX), 0x...).
The very idea of allowing the nil value for slices seems to be very strange and inconsistent, as slices are struct types, not pointer types in Go (they contain a pointer and other members). Just one of the many ways that builtin types in Go are fundamentally different from user-creatable types, I guess...
To be honest, that's what I'd expect. What do you dislike about that result, and what would you prefer to see returned? Jump straight to 404?
returning a single object without an array to represent one item.
So an array if there's multiple results, and a bare object for a single result? That's unpleasant.
That's my pet peeve. I completely understand the logic - using the HTTP status code to show the result of interaction with the resource is very RESTful - but my complaint is that unless you provide more context, a 404 doesn't tell me if I'm getting a response of "that resource doesn't exist" vs "you're accessing a url pattern that will never work".
So if you want this random internet user to be pleased, never return a 404 response unless the caller is able to see this difference. (Usually having SOME form of body unique to the API is sufficient to prove the 404 is not because of a bad API call).
Giving me the HTML to your site 404 page when I called a non-HTML API is likewise sad-inducing.
It’s inconsistent and means I need to write special case code to check for it, when before I could choose to. It should return an empty array.
> To be honest, that's what I'd expect. What do you dislike about that result, and what would you prefer to see returned? Jump straight to 404?
I'd expect an empty array to represent no items. It's the difference between "" and "[]".
I saw the same thing when working with PHP consuming data from a SOAP endpoint. First I thought PHP is stupid. But then I realized that XML can’t model single item arrays versus single objects. They look the same. JSON is better that way. You can model empty arrays and single item arrays.
<results>
<result>
<property>value</property>
...
</result>
</results>
I don't really see the problem.Looking at the XML when a list has only a single element, you wouldn't know if there could be more. You need an XSD to accompany the XML, which is what is typically provided.
When looking at a JSON document you might run into the same situation where the document you received doesn't contain all possible elements, and you wouldn't be the wiser. You'd still need a proper JSON schema to accompany the document.
if ismissing(x) then
x = empty
end if
if isempty(x) then
x = ""
end if
if x is nothing then
x = new foo
end if
if right(typename(x), 2) <> "()" then
x = Array(x)
end ifHow were you able to do this when the standard maximum length of a query string is 1024 bytes? I guess you could flaunt the standard as you were responsible for the backend
We had some issues because there was no real security on the API of our NLP tooling. So we put NGINX in front of it to create a from of API key auth. NGINX would deny the larger messages by default, so we had to increase some parameter so it would pass the large documents. And indeed, since this was only relevant in the backend, it didn't matter. For the front-end we built our own API that was a lot more sensible.
https://stackoverflow.com/questions/417142/what-is-the-maxim...
this happens when you add JSON version for old XML-based APIs (seen this multiple times)
...without using an XSD schema. With a schema,not an issue
Basically, GET to posts would always return an array of posts. Whether there are 0 (empty array), 1 (just one object in the array), or many (array with n length). This makes API logic way easier to handle without having to check what structure I received even with a 200 status code
If it's sometimes an array and sometimes null, I need branched logic for each call.
I also like that it encourages flatter data models.
I had to work with an API where the company decided everything should return http code 200 (well, at least all 4XX errors), and give the error code in the JSON response, mixing existing 4XX errors and their own errors.
When pointed out, the support answer was "we chose to give meaningful error messages instead of HTTP codes, that's why we respond with 200 in case there's an error in the request". Not the answer I was expecting.
Another annoying practice is to answer 2XX, put the request in a queue, and not provide ANY information about the queue, which can be minutes or even HOURS long. Debugging is a nightmare. The one I worked with who did that did not even have the excuse of being a startup or small company.
If all of your errors line up perfectly with HTTP, I guess this could work. But if you've got something that doesn't fit, or two things that would map to the same one, it gets weird.
And then you have http client libraries that do great things like only return response bodies if status 200, or only return http statuses they were aware of. It's not very RESTful to just return http 200 with an embedded application status, but it's easy and consistent, and I would not write an HTTP api otherwise, unless I was had a good reason to follow some existing spec that used statuses.
Even then, if the server returns 400 (Bad Request) the server can still attach a response body to that, in plain text/plain, application/octet-stream or even application/json, which could contain elaborate information.
The former when the problem is on the client side, the latter for a problem on the server.
And you can still send a descriptive body for the error, if you so choose.
Both of these are 404 (or 410 for permanent caching) responses according to HTTP, though they have very different reasons for "non-existance".
404 is only for "the request makes sense but that specific resource doesn't exist".
So here's the deal with this pattern...If you're returning a typed error response, something the client application should interpret, you want to be able to know which error responses will actually have that body and will not be a generic error like a 404 or a 503. If the response code is 200, you can be generally sure that the response came from the target host. Thus, the client knows they can parse an api level error from a 200 response and they should not attempt to parse non-2XX responses. I don't love the pattern but its not completely pointless.
Does anyone know if the HTTP spec guarantees codes in 4XX range should only come from the intended host? It seems like 400 is a safe bet but I've never double checked myself.
I don't see the problem here. As a developer I'd much rather receive a standard json packet with information helping me figure out what went wrong.
I really don't understand your complaint here, I've designed and worked with both types of API's, and I find the standard json format to be far easier to deal with.
And in my experience, having an out-of-body/band general indicator that doesn't require you to parse message responses makes things WAY easier.
Well-designed APIs do both.
You want to talk about inconsistent? How about a 500 error may or may not result in the standard response format you're expecting because it may be coming from the server and it may be coming from the API.
I'd much rather my 500 errors be legitimate server problems.
They actually are. Things besides your app code can response with 404 and 503 but not your error body. 4XX and 5XX bodies must be parsed more carefully and cannot be assumed to have a consistent structure with the same level of trust a 200 response would.
Http codes are nice but it makes api error parsing much more complex so there are some trade offs.
The big fat elephant in all this is simple; None of our fucking opinions matter one god damn bit to the end client. Being originally designed to you know, consume hypertext over the hypertext transfer protocol, clients can and will do whatever the fuck they want with the status codes.
And honestly it kinda make sense when you think about it that way. “404, wrong url” and “404, id not found” should be different errors.
I'd actually argue the opposite, though I can definitely see both sides.
To me, because two systems communicating RESTfully need not know anything about each other, responding to "please give me the resource as this URI" with "there is no resource at that URI" seems perfectly correct. I don't really need to know the specifics of how the remote machine is dealing with my request.
If more detail is required you can always include a message in the request body, which I think should be standard practice for handled errors anyway.
I much prefer colleagues who can say, woah that was dumb thanks for informing me of a better way. Making excuses doesn't help anyone unless one has a valid logical reason they did a certain thing, otherwise I DONT WANNA HEAR IT.
I've done something like this in the past. There was a (horrible) reason; old versions of Android had terrible built-in HTTP stuff and tended to break on any 'unusual' HTTP responses (for instance, 204), especially where HTTP compression was enabled. By far the safest way to support clunky old Androids turned out be be just return 200 for everything with the real code embedded elsewhere...
Instead of building your api according to the default Android client ( ps. Lookup BFF microservices)
FWIW, I think the last Android phones with these client issues have probably died by now (it got mostly sorted out in 4.3 or so IIRC); this isn't a current concern.
Ugh it was frustrating.
(to their credit, the docs are very complete and clear, even if their API design is questionable)
Sounds like that decision came from someone who didn’t spend much of their career consuming APIs.
I could go on looking back the projects I've done.
This so much. One of our main adtech vendor is lagging behind on the API front. We've been chasing them for a while on when they'll be up to date so that we can build on top and they get back to us on how their other customers don't really want an API.
Of course, no one (beyond us tech crowd) goes to bed thinking oh I need an API to interface with my DSP. But I'm sure they'd be delighted about what the API can enable them to do.
Here's an advice if you are building / improving a pretty consequent SAAS product : Your UX sucks. Not that it is awful but it is likely not optimised for what your customers are doing, simply because you keep adding features and now it's bloated.
And I don't mean that it is an awful thing, it is the nature of such product to keep growing, because marketing, justifying salaries and obviously adding value.
Chances are, 80% of your customers are only using a good 20% of the features you offered and they'd rather have something that is tailored for efficiency to address their main pain point. So either you step up your game to offer that flexibility or you get your API game up to speed. Your competition might beat you to it and I know which product I'll choose.
Re: hiding docs:
Luckily, this can be easily done by putting the documentation behind a login screen... consider making your documentation a PDF file...
DJI's release notes for the DJI-SDK are only available for DJI registered developers. As a zipfile - of a single pdf doc.
The power is in your hands; use it. Don’t play their games.
* Aggressive rate limiting that makes it hard to use the API in real world situations. Especially if there is no documentation about what the limits are.
* Throwing errors with no explanation about what went wrong or how to correct it. Especially effective if given two very similar requests, one succeeds and the other one fails.
* Throwing errors randomly / when under load / when not under load / based on the phase of the moon.
* Having absolutely no example code anywhere in the documentation.
* Requiring hundreds of lines of code to even establish a connection to the API.
* Requiring a specific client library to access the API. Extra points if it's Windows only or requires a specific out of support version of Python 2.
Extra bonus points for intermittently using case-insensitive but case-preserving identifiers.
Microsoft Azure storage APIs is a prime example of this with 4-5 different sets of identifier restrictions dependening on what you're naming. (Including one that allows any valid C# identifier, for which the documentation conveniently refers to the ECMA specification of C#).
Also enabling some special characters like # when creating entities, while knowing that # will be interpreted differently when fetching entities. Such that entities with # in the key cannot be fetched or deleted, but only created.
Extra extra, bonus points for retaining # support in the interest of backwards compatibility :)
Their recommended solution: Make sure all of your intervals overlap by several minutes to avoid any problems. :-P
Even with multiple keys, if they are all god-mode it’s difficult for a central operations team to give internal users API access without risking unauthorized changes or audit findings in regulated environments.
There should be a pricing model to cover basic expenses made by the API usage.
Maybe you wonder why on earth it should be legally allowed to process automatically system data?
We have a lots of great services online. But we can not move further, integrate them into even better ones, because of lack of APIs and bot bans.
Without it, we wont be able to create high level services people expect. And currently if these will be provided, than only by companies that have Monopoly over vast parts of online offering. Because they can make more monopolistic deals with service providers.
Another problem is that service owners have adventage over users. Because they can process users data to drive business decisions torwards them. But users can not process thr same data for their adventage. With more and more complicated systems user ends up being dependant on the company service and has no possibility of validation.
And this means even more trouble than we have today. So ye, open programmatic access as a human right.
Larger companies love regulations like this because they can afford it, and it keeps smaller competitors from ever growing to be a threat.
I'm not saying they should be able to do whatever with data - but for such providers, manually replying to an email is preferable than implementing a complicated technical solution they can't understand (and will often likely mis-configure, exposing your data) when they just want to sell hats.
I also agree that the big players would roll it into their core offering which would make life easier, but I'm wary of monocultures. A lot of people are already a bit annoyed at how much Wordpress is out there and this would just be another reason to skip a smaller (or bespoke) alternative and raise the barrier of entry for anyone thinking of making an alternative. But if we're agreeing that no one is forced to do it and scraping is OK, that's fine.
I think mandating API for certain industries like banking is a good idea, but I'm not so supportive of having it apply all the way down to my local hair salon. They have enough to worry about.
Recently I'm writing code that interacts with API of a Enterprise Product (fairly new, less then 3 years old) and its driving me crazy. They version every single API endpoints separately. So endpoint A to create a user is at version 7 but endpoint B to assign a group to a user is at version 4.
WTF?
Google Firebase has no API for creating projects. Therefore it is impossible to use Terraform or other IaC (Infrastructure as Code) tool to provision backends that send push notifications to Android apps. Manual steps are required. In this way, Google Cloud prevents its customers from using SRE best-practices.
https://github.com/terraform-providers/terraform-provider-go...
Google as an organization is simply unable to focus on users.
But in general, a lot of things on the web that you would expect. Using Stripe, Paypal, Ebay, Amazon, Google Maps, etc have APIs into their services.
From a dev perspective, there are industry standard APIs which a range of products support, and to design a new product that we want to sell, we have to use said APIs and work with different providers and customers. There are so many differing APIs to do the same thing that we have an internal team whose job is to write an internal API that internal customers use to interface with all the external APIs. This model scales well, as this API-of-APIs team can integrate new solutions transparently to the internal customers, so we don't have to rewrite products just because an external API/provider/customer/etc changed. (back in the day this was with straight databases and apps, and the intermediate layer was called "db apps", and was basically an early API)
I run a small b2b app between two completely non-technical businesses. There is absolutely no need for me to have an API available to them, they’ve never asked for it and have no desire or ability to consume it.
Believe it or not, there is also an expense to offering an API! An API is a product offering like anything else, and products need customer support. API products need advanced support because they are technical in nature, you can’t use a call center for this type of support.
And I don’t really want random joes signing up for my API and doing god-knows-what with it. I’d much rather create a relationship with you so I know what you’re trying to do (so you don’t bring down my servers in the middle of the night or run up a huge bill because you’re use case is a little beyond what I can support).
The other points can just be summarized as “have a perfect API and perfect docs”. Ok. Thanks. Can you show me an example of this in the wild? Didn’t think so.
The better suggestion is to analyze your business and decide if offering an API furthers your businesses’ goals.
> There is absolutely no need for me to have an API available to them, they’ve never asked for it and have no desire or ability to consume it.
Whenever I've used "small b2b apps," especially between non-technical businesses, if you don't have it I'm not asking for it. I know how hard it is to be a solo founder or part of a very small team so I'm either going to use your product as-is, or I'm not going to use it.
> API[s]...need customer support
There are plenty of small, niche APIs where there is out-dated documentation and not much else. I'm saying that's a great experience, but let's not pretend it's illegal to have an API without on-demand live support.
> And I don’t really want random joes signing up for my API...
The reasons listed here can all be handled via code. There are very few reasons to prevent automated sign-ups.
> The better suggestion is to analyze your business and decide if offering an API furthers your businesses’ goals.
If you think it can't, you're just not being creative enough. Every single API with more than 2 users is being used in ways its designers hadn't originally thought of. Many brains are better than one brain and you can often get more (and better) ideas from what other people are doing with your tech than you ever could on your own.
You’re asking for access to the heart and soul of a company and demanding to pay the same price as a customer who asks for much less. I’m having a hard time understanding why I should pursue you as a customer when I can get the same money out of someone who is way less demanding.
It also means you can scale if you ever do need to add a customer that wants to make use of an API.
Saying not to do an API because customers don't want it is similar to not using source control because you're the only developer.
Turns out it doesn’t piss only customers but developers (of the API) as well.
It's eerie, almost as if the author tried to use our system and then decided to write this...
Charges for use. Manual documentation. Idempotency. A weirdo protocol.
Even worse, they seem to forbid any sort of programmatic access in their ToS.
Debugging is boring. Wouldn't you rather appeal to customers who write bug-free code on the first try?
To really show disdain for your customers, use a proprietary protocol so that language support is limited to the client libraries you provide, preferably as binary blobs that are never updated. If you design it carefully, a proprietary protocol can be difficult to understand and impossible to debug, too.
Alternatively, you can use SOAP (Simple Object Access Protocol). According to Wikipedia, SOAP "can be bloated and overly verbose, making it bandwidth-hungry and slow. It is also based on XML, making it expensive to parse and manipulate—especially on mobile or embedded clients" (https://en.wikipedia.org/wiki/SOAPjr). Sounds like a win-win!"
I remember when the early days of Amazon S3, trying to write Bourne shell scripts using shell built-ins and single purpose UNIX utilities to form the HTTP and interact with the servers, instead of scripting languages with libraries like Perl, Python, Ruby, etc. This is how I interact with HTTP servers normally. I never have any problems keeping things simple and dependency-free.
To do this with S3, it felt nigh impossible. There were small errors in their documentation of how things actually worked. It felt like they were intentional just to trip me up. I know they were not.
The official recommendation back in those early days of AWS was to use one of the protocol options provided by Amazon, HTTP or SOAP. You would think, heh, I will avoid SOAP and keep it simple. I will just use HTTP.
The truth is both required using scripting languages with libraries. Amazon's own utilities were written in Java. I know developers have their reasons for making these choices, but as a user, that complexity really put me off.
From my perspective, this ACM article is right on point.
"When I see a top-down description of a system or language that has infinite libraries described by layers and layers, all I just see is a morass. I can't get a feel for it. I can't understand how the pieces fit; I can't understand something presented to me that's very complex. Maybe I do what I do because if I built anything more complicated, I couldn't understand it. I really must break it down into little pieces." - Ken Thompson http://genius.cat-v.org/ken-thompson/interviews/unix-and-bey...
In my current life I work mostly with JSON and a typical workflow involves checking API documentations, querying the endpoints, and understanding the structure. I need to own the mapping between JSON and domain objects.
In a previous life I worked with .NET and C#, mostly SOAP APIs. A typical workflow involves right-clicking somewhere, pasting the link to the SOAP endpoint's WSDL file, and automagically getting a collection of strongly typed classes that I can manipulate directly and operate on as if they were domain objects.
The idea that when using SOAP one spends any time (manually) parsing and trying to make sense of XML is a misconception.
To put it in a modern parlance, one shouldn't compare SOAP to JSON. SOAP is JSON + Swagger, with the Swagger integration costing 0.
> There were small errors in their documentation of how things actually worked.
that sucks, but I’ve run into that with people speaking “http” and not just special protocols.
And then he casually offers an API that does different things on first and second call as the "good" example. If you have a "create a virtual machine" API it better create a fucking virtual machine. If I call the damn thing twice, I expect to have two VMs. If there is some sort of unique argument like create a named VM, I would expect API to throw an error if the name is already taken, no to just return like everything is normal.
And this guy is being all snarky about API design?
I work in mobile games; because someone might play in a tunnel or bad network area, I need to make sure that every request is retry-able.
To do that I generally include a GUID of some kind in the request; if the client says "create an entry for XXYY," there's a chance that the request will get to the server but the response will fail to reach the client.
If the client is able to retry the request (with the same GUID) and get a success response, then I can have the retries handled transparently in the communication layer; all the client code needs to know is "I made this request and it was a success," without any knowledge of how many tries it took.
If the second/third/etc request returned an error of some kind, I wouldn't have a good "success" response to hand back to the game code. (I'm assuming the "success" response contains some information that the game code needs.)
An advantage of this style is that if the client dies or times out during the (long) operation, it can retry and get the same answer instantly.
let new_id = generate_id();
retry_with_backoff(() => api.make_vm(new_id));
retry_with_backoff(() => api.do_thing_with_vm(new_id));
This works even if any individual API calls fail, or if the API call makes it to the API server but the response fails to make it to the client.If the APIs aren't idempotent, then you would have to do this to get the same behavior:
let new_id = generate_id();
retry_with_backoff(() => {
try {
api.make_vm(new_id);
} catch (e) {
if (e.info && e.info.code === 'vm_already_exists') {
return;
}
throw e;
}
});
retry_with_backoff(() => {
try {
api.do_thing_with_vm(new_id);
} catch (e) {
if (e.info && e.info.code === 'thing_already_done') {
return;
}
throw e;
}
});
This nonidempotent API is harder to use. Someone that doesn't know about these error codes or the fact that the API isn't idempotent will write code without the try-catch blocks that doesn't handle retries correctly. With the idempotent API, users fall into the pit of success where things just work without them having to know the details about each of the edge cases.The nonidempotent API is exposing some extra data to the user, but it's not super useful. You basically always want to treat the vm_already_exists error identically to a success response. Maybe you also want to log some data about how many retries were necessary so you can figure out how spotty the network connection is, but there's no reason that couldn't work with the idempotent API either. The idempotent API could include a header about whether the action was already taken previously.
Consider how TCP connections are used by applications. Your application doesn't have to opt in to handling packets that were resent. The fact that some packets had to be resent is by default just an implementation detail. You have to opt in to get information about the resent packets; by default they're handled like regular successful packets. Idempotent APIs are about making handling retries work by default in a very similar way.
try:
vm_id = api.make_vm()
except SomeError as e:
log.error(e)
else:
res = api.do_thing_with_vm(vm_id)
and in your example, if we are generating ids ourselves, we still have to verify that we got the right VM. If your ids are provably unique, there is no reason to generate them, the API can take care of that, but if you want something like a named entity, you have a problem. What if the name is already taken? So your code would look more like new_id = generate_id()
try:
vm = api.get_vm(new_id)
except VM_DoesNotExist:
vm = api.make_vm(new_id)
except SomeError as e:
log.error(e)
else:
api.do_thing_with_vm(new_id)
because if the make_vm API simply returns a VM whether it was created or not, it is entirely possible that you are getting a VM that is busy doing something else for some other process.