11.3 Libraries and APIs: Reading Definitions, Making Calls, and Weighing Trade-offs
Key Takeaways
- A library is a collection of prewritten, reusable code; an API (application programming interface) is the documented set of procedures, parameters, and return values through which a program uses a library or service.
- To use an API correctly, match each argument to the parameter in the stated order and type, and store or use the returned value; calling sqrt ( x ) on a line by itself computes a result and then discards it.
- Reasons to use a library include saving time and relying on tested, efficient, secure, standard code.
- Reasons not to use a library include license terms or cost, dependency and security risks, unneeded size, platform limits, and learning goals that require students to write the algorithm themselves.
- Math functions, random number generation, graphics, date and time handling, maps, weather data, payments, and speech recognition are all commonly provided through APIs.
What this competency asks
ETS asks you to know how to use libraries and APIs:
- Identify correct call(s) and use of return values given an API definition.
- Identify reasons to use or not use libraries in place of writing original code.
- Identify applications (for example, math libraries and random number generation) that use APIs.
Libraries and APIs
A library is a collection of prewritten code, such as procedures and classes, that programs can reuse. An API (application programming interface) is the contract for using that code: the names of the procedures, their parameters and types, what they return, and what they do. An API is an abstraction (Section 4.1). You need to know what a procedure does, not how.
APIs also connect programs to services over the Internet. A web API lets a program send a request, for example for a weather forecast for a ZIP code, and receive a structured response, often in JSON format. Web APIs commonly require an API key and limit how many requests you can make.
Reading an API definition
Questions supply a table like this one. Use exactly what it says.
| Procedure | Description |
|---|---|
double pow ( double base, double exponent ) | Returns base raised to the power exponent |
double sqrt ( double x ) | Returns the square root of x; precondition: x ≥ 0 |
int abs ( int x ) | Returns the absolute value of x |
int randomInt ( int low, int high ) | Returns a random integer from low to high, inclusive |
Checks for every call:
- Name and number of arguments:
powneeds two arguments. - Order:
pow ( 2, 10 )is 2¹⁰ = 1024, butpow ( 10, 2 )is 100. - Types: pass the types listed. The return type tells you what kind of variable can hold the result.
- Preconditions:
sqrtrequires x ≥ 0. Check or validate before calling. - Use the return value: store it, print it, or use it in an expression.
Correct and incorrect use
// Distance between points (x1, y1) and (x2, y2)
double d ← sqrt ( pow ( x2 - x1, 2 ) + pow ( y2 - y1, 2 ) )
// Roll a die
int roll ← randomInt ( 1, 6 )
// BUG: the return value is discarded; x is unchanged
sqrt ( x )
print x
// FIX
double root ← sqrt ( x )
print root
A frequent distractor calls a value-returning procedure as if it changed its argument. abs ( n ) does not change n; n ← abs ( n ) does.
Class-based APIs work the same way. ETS's sample string question gives a table for a String class (substring, toUpperCase, length) and asks which sequence of calls produces a given output. Method calls use dot notation: value.toUpperCase ( ).
Why use a library?
| Benefit | Explanation |
|---|---|
| Saves time | No need to write and debug common functionality |
| Reliability | Widely used libraries have been tested by many programmers |
| Efficiency | Library code is often carefully optimized |
| Security | Getting cryptography, password hashing, and input parsing right is hard; vetted libraries avoid subtle flaws |
| Standardization | Other programmers recognize and understand common libraries |
| Access to services | APIs connect to maps, payments, weather, and machine learning that you could not build yourself |
Why not use a library?
| Reason | Example |
|---|---|
| License or cost | A library's copyleft license conflicts with a closed-source product, or its price is too high (Section 3.1) |
| Dependency risk | The library is abandoned, changes its API in a breaking way, or has a security vulnerability that affects every program using it |
| Size and performance | A huge library is used for one small function; a tiny embedded device cannot hold it |
| Poor fit | It does not quite meet the requirements, and working around it costs more than writing custom code |
| Privacy or availability | A web API sends user data to a third party, or fails when the service is down or rate-limited |
| Learning goals | In a CS class, students write their own sort or search to understand the algorithm, even though a library version exists |
For a teacher, the last row matters. "Why not just call sort?" is a fair question in industry, but in a classroom the goal may be learning the algorithm itself.
Applications that use APIs
| Area | Typical API use |
|---|---|
| Math | Square roots, powers, trigonometry, rounding |
| Random number generation | Dice, shuffles, simulations (Section 5.3) |
| Graphics and games | Drawing shapes, handling sprites and sound |
| Date and time | Time zones, calendars, measuring elapsed time |
| Files and networking | Reading files, sending web requests |
| Maps and location | Geocoding addresses, directions |
| Data and science | Statistics, charts, machine-learning models |
| Communication | Sending email or text messages; signing in with an existing account |
| Payments | Card processing through a payment provider's API |
| Accessibility and AI | Speech-to-text, text-to-speech, translation |
Documentation makes an API usable
A good API comes with documentation that states each procedure's purpose, parameters, return value, preconditions, errors, and an example (Section 10.5). When you write your own procedures for others to call, you are designing an API, so give it the same care.
An API provides double pow ( double base, double exponent ), which returns base raised to exponent, and double sqrt ( double x ), which returns the square root of x. Which statement correctly stores the distance between the points (x1, y1) and (x2, y2) in d?
A teacher asks students to write their own sorting procedure even though the language's standard library already includes a fast, well-tested sort. Which reason best justifies this choice?
An API defines int abs ( int x ), which returns the absolute value of x. After int n ← -7 and then the statement abs ( n ), what is the value of n?
A classroom game needs a fair six-sided die roll. Which approach uses an API appropriately?