r/C_Programming • u/rias_dx • Jul 21 '26
Question what should be avoided when designing an API?
What kind of thing you see beginners doing, when designing an API, should be avoided in your opinion (or just based on facts)?
I don't have too much experience creating interfaces for clients and every time i write a line of code, start thinking if it's a good idea or it's a bad decision that will break my legs in future. I get paralyzed for a considered period of time instead of just coding it.
edit: thanks a lot (really) for all answers.
67
Upvotes
56
u/aalmkainzi Jul 21 '26
Leave allocation to the caller if possible.
For example:
vs
imo the second is always better (although i usually make it return an error code rather than void)
24
u/Innowise_ Jul 21 '26
One thing we’d avoid is unclear ownership. If the API returns a pointer, callers should immediately know who allocates it, who frees it, and how long it stays valid. The same goes for errors—define one consistent strategy early instead of mixing return codes, nulls, and global error state.
71
u/its_artemiss Jul 21 '26
making unreasonable assumptions such as
that all function calls we be made from the same thread,
that the user doesn't care how memory is allocated,
that there is a global memory allocator
that your functions that take or call callbacks need not be reentrant
that strings are terminated by a null sentinel
that strings only contain certain byte sequences
that strings don't contain certain byte sequences
using global error flags (akin to errno/ntstatus)
5
u/DeGuerre Jul 22 '26 edited Jul 22 '26
On top of what everyone else has said, I have a few guidelines that help me:
1. Write the usage code first.
This is the cure for paralysis. Write the code that you, as a user of the API, would like to write. That's your start.
The temptation is strong to include the kitchen sink. A good API tries to minimise its "surface area", which is how much of the API you really need to know just to get a job done.
2. It's okay if initialisation is a little complex, if it makes everything else simpler. Provide a simple default if possible.
A lot of people have mentioned allocation and truly-fatal errors, and these are both good examples. Initialising the API might be complicated if the user needs to tell the API how to allocate memory. That's okay. But also provide a simple default, e.g. one that uses
malloc.As an implementation detail, it's good practice to make the simple one call the complex one.
3. The rules of three are never wrong.
The rules of three are:
Rule 2 is good to know, but it's probably not relevant for you right now. It's for APIs with multiple "backends" (e.g. think of an API that abstracts some operating system service for different OSes, or a graphics API for different graphics cards). This probably isn't what you're dealing with here.
The upshot of Rule 1 is that no matter what you do, there will be some tweaking to do until your API has been used in at least three different programs.
16
u/dbear496 Jul 21 '26
"Main-character syndrome" when a library requires it be first at something, making it possibly incompatible with other libraries or applications that want to be "first". For example, a library that implements
main, or a library that must be#included first...like pybind11.14
u/PlacentaOnOnionGravy Jul 21 '26
accidentally making internal implementation decisions part of the public contract because Once clients depend on them, changing your database, workflow, or service boundaries becomes much harder.
Believe me you don't want that smoke
9
u/NoneRighteous Jul 21 '26
Not writing basic documentation with the right level of detail. I should be able to get an overview of what a function does and what it expects quickly and more details when I need them. SQLite gets this right imo, you don’t have to guess what happens when you use that API
8
u/TheThiefMaster Jul 21 '26
A few more:
void* contextparam for anything involving callbacks8
u/keithstellyes Jul 21 '26
This might be controversial, but I get mildly annoyed when libraries define the standard types that have been in C by the 00s... stuff like
CoolLibrary_TRUE,CoolLibrary_NULL, or even egregiously,CoolLibrary_INT.Maybe just my taste, but in a modern C environment it's tedious and makes me worry if
CoolLibrary_TRUEmight be a different integral value fromtrue7
u/evincarofautumn Jul 21 '26
Don’t jump into writing code immediately. A little planning pays off.
The main thing you’re trying to catch is counterexamples where someone (including future you) could accidentally hold it wrong by doing something that looks reasonable.
A typical API is either an algebra or a state machine. You’ve got either objects and ways of combining them, or states and transitions between them. Objects/states become API types, operations/transitions become API functions.
Consider representations for types that can’t get into invalid states, and what checks you need to prevent invalid transitions.
Examples:
A size/count/length should use
size_t, notint. “Possibly as low as −216, or maybe lower, and possibly as high as 216−1, or maybe higher” is rarely what you want.Even if a type only serves as documentation, it adds value.
enum UserType { UserTypeNormal, UserTypeAdmin }is both a lot clearer thanbool isAdmin, and much easier to change later on when you discover you also needUserTypeModerator.Drawing the design out by hand on paper and explicitly writing down your assumptions about it will clarify it a lot. What properties do you expect it to have? You can test and enforce these properties in one place, like when an object is created, and then assume them, instead of defensively sprinkling
assert(is_well_formed_thing(thing))everywhere.I try to make things associative/commutative/idempotent/monotonic as much as possible, especially when considering concurrency or networking. That way if events get reordered or actions get retried, it doesn’t matter. Always remember you can solve a problem by making it not a problem.
7
u/imaami Jul 21 '26 edited Jul 21 '26
Not really about the API, but indirectly also about the API: a library should never
abort(),assert(),exit()or do anything that curb stomps the main process.A library ragequit is almost never what the user wants as a programmer. If I use a library I want to know exactly why something failed and live to tell the tale. I may have all kinds of critical things going on that absolutely require a controlled teardown.
In summary, the API must implement considerate and sufficient error reporting. If something goes irreversibly wrong, it's OK to return an error that essentially means "if you call any of my functions again I will fuck you over", and then it's OK to crash a library iff that ultimatum goes unheeded. Assuming you've documented everything properly of course. When the programmer has a choice to either conform to what the library's API spec says or find out what happens if not, it's on them.
6
u/Professional_Ant6414 Jul 21 '26 edited Jul 21 '26
Decide on a consistent naming scheme from the start and stick to it. Pascal case? Camel case? All lowercase? Underscores or no? Verb/Object or Object/Verb? Prefix every function call with your API name (or a shortened form thereof)? Full names or compressed names?
I'll tell you one thing to avoid from the start because it's almost never correct: don't use full uppercase for acronyms unless you're using Ada-style naming (capitalized words with underscores, so
Create_XML_Node). Either go all-lowercase (create_xml_node) or only capitalize the first letter (CreateXmlNode; this is an official rule at Microsoft, actually), but notCreateXMLNode. It makes it hard to see the word boundaries without applying active thought.4
u/sciencekm Jul 21 '26
Do not create an API that maintains a static internal state.
One example of such a bad API is strtok(). You cannot have an outer loop using strtok on a string and an inner loop operating on a different string, because strtok has only one internal static state. We had to invent a new API - strtok_r() to fix this.
2
u/Deux109 Jul 21 '26
Maybe not a C specific piece of advice but exposing too much to the end user. As a consumer it can be a lot especially without good docs. Also, most of the time APIs should be written so that they can hit (almost) every code path from a few public methods which is why a lot of unit testing is designed this way.
2
u/TraylaParks Jul 21 '26
Some folk like to have a 'version' field in their API so that they can extend the API later without punishing folks who don't care to update to the new standard.
Also, you can get a good feel for an API by actually using it. A lot. Something that seems totally reasonable on paper can end up being unfun and cumbersome during real world use. TLDR; eat your own dog food :)
2
u/DreamerSleeper Jul 27 '26
Casey Muratori has a decent talk on API design on YouTube here https://youtu.be/ZQ5_u8Lgvyk?si=0Bdgap1Xr_jM0VoB
1
u/duane11583 Jul 22 '26
remove the implementation from the api.
example stm32 has a set of timers and adcs used for three phase motir control.
do you make a timer api with motor features? or a motor api?
1
u/demetrioussharpe Jul 22 '26
Any assumption about the implementation of the consumer or the producer of the API. It typically should be strictly data-centric & stateless.
1
u/Stu_Mack Jul 21 '26
Avoid allocating anything that you don’t have to allocate, and make sure the abstraction jump is total. The high level has no idea the lower levels exist.
1
u/Natehhggh Jul 21 '26
Im a big fan of Anton's answers in this wookash episode when he was going over api design, he seems to have a very good understanding between good/bad apis, and the ramifications of choices you could make as a developer.
I don't think it's right for me to try to summarize him too much other than write the simplest case first using as little features as possible, and don't make your problems the users problems.
https://youtu.be/7lOupIR1620
0
u/AccomplishedSugar490 Jul 21 '26
Not exclusively in API, but it is a typical place for it - solutions without a problem. I could elaborate, but until I know you need one, any explanation would also be an example.
-2
u/Olovico75 Jul 21 '26
Not including CORS policies, logics and constrains at the root of the initial specifications can cost a lot to the design on a tight time frame.
-2
u/Pupation Jul 21 '26
Don’t allow path parameters in URLs that aren’t a finite set of numbers and characters. Might seem obvious, but I’ve seen people put e.g. usernames in the path (not query string) and run into issues at the server.