Post on 13-Feb-2017
Effective API Design
Bansi Haudakari
API’s Are
For the Developers,
By The Developers
And
Of the Developers
- Bansi Haudakari
Who Am I?
• An API Developer• An API Consumer• An API Designer• A Seasoned JAVA Programmer
who has been consuming JAVA API’s since JDK 1.0 And Other Open Source APIs For Software Development
Agenda
• What is an API?• Driving factors Of an API• Principles of Effective API Design• API Design Guidelines• API Design In Action• Value Of Great APIs• Pitfalls of mediocre APIs
What is an API?Application Programming Interface provides a way for developers to interact with and consume a service.
Analogy: Electrical Sockets
• APIs are gateways between Services and Consumers, providing consumers access to services through various interfaces
Example: Service : Electricity AND Consumer : Plug
• Our laptops, consumes electricity through a socket. Through its own “API,” a USB socket, it can provide that same electricity service to charge other devices.
Driving Factors• Design of CHM• Business Agility : Business Logic is exposed thru
APIs thereby enabling customers to focus on innovations
• API Economy : Businesses are developing “API products” as new sources of revenue. Expedia generates over $2 billion thru data made available through their API
• Internet of things: The number of things that can be connected is growing fast; everything from your coffee pot to your thermostat to your car can now be accessed thru APIs
Principle 1 : Design First API • With Design-First approach, focus is
on well-defined API spec’s instead of implementation concerns.
• With an Design-First API approach, rather than implementing an application and then building API on top of it, first create the interface and then put the back-end logic into place - whether it be cloud-based or on-premise.
• An optimal API design enables applications developers to easily understand the purpose and functionality of the API.
• It also allows organizations to focus on getting API design right before investing in back-end implementation,
• The best way to design an API that developers want to use is to iteratively define the structure of the API in an expressive manner and get feedback from developers on its usability and functionality
• As the API is designed, application developers can interact with it and test its behavior, thanks to an integrated mocking service that returns the values a call to the live API would produce.
• There is no such thing as a one-size-fits-all API• An API should be optimized to fulfill a specific
business request in a specific context.• Optimize API for a specific use case e.g. – coarse or fine-grained– constraints e.g. network trips, latency and data
size so API should be designed to limit backend calls and minimize the size of data returned
API Design Guidelines• Know the requirements• Write use cases before you write any other
code• Look for similar APIs in the same library• Define the API before you implement it
otherwise it embodies the evils of implementation-driven APIs i.e. don’t let implementation considerations leak into the API, apart in exceptional cases
API Design Guidelines• Consider the perspective of the caller• Make sure each method does only one thing• Make all method calls atomic• Limit the number of Mutator methods i.e.
set/get methods• Favor generic methods over a set of overloaded
methods• Avoid long-running methods• Avoid forcing callers to write loops for basic
scenarios
API Design Guidelines• Avoid “option” parameters to modify behavior• Avoid non-reentrant methods• Do not strengthen the precondition of an already released API
method• Do not weaken the post condition of an already released API
method• Do not add new methods to released interfaces• Do not add a new overload to a released API• Favor interfaces over concrete classes as return types• Favor empty collections to null return values• Consider making defensive copies of mutable parameters• Consider storing weak object references internally• Avoid parameter types exposing implementation details
API Design Guidelines• Avoid returning references to mutable internal
objects• Consider a builder when faced with many
constructor parameters• Consider returning immutable collections from
a getter• Consider read-only properties• Document method preconditions• Document the performance characteristics of
the algorithm implemented
Measure API Design• Conceptual Complexity Measurement :
– double digit : use case is simple ; – single digit : complex ; – negative number : time to re-design– In your code, Count the number of name constructs used in API
• try { AuthenticationProvider20 provider = new LocalAuthenticationProvider19();
SearchCriteria18 criteria = new SearchCriteria17(EntityName16.USER15); criteria.addPropertyToFetch14(PropertyName13.COMMON_NAME12);….
while(iterator.hasNext()4){ Profile3 profile = iterator.next()2; Property1 commonName =
profile.getProperty0(PropertyName.COMMON_NAME); Property phone = profile.getProperty(PropertyName.PHONE); System.out.println(commonName.getValue()-1, “ ”, phone.getValue()); } } catch(AuthenticationProviderException-2 e) { }
API Design In ActionBefore After Design Rule
public long[] getAllMessages() throws MailboxException;
public abstract SortedSet<T> readAllMessageHeaders() throws RemoteException, MailboxException;
Favor collections over arrays as parameters and return valuesEnsure no boilerplate code is needed to combine method callsReserve “get”, “set” and “is” for JavaBeans methods accessing local fieldsThrow checked exceptions only for recoverable errors
API Design In ActionBefore After Design Rulepublic void markRead(boolean read, long[] ids) throws MailboxException;
public abstract void markRead(Collection<T> headers) throws NullPointerException, RemoteException, MailboxException;
Make all method calls atomic
Avoid Boolean parameters
Ensure no boilerplate code is needed to combine method calls
Consider generic methods
Consider method pairs, where the effect of one is reversed by the other
Favor generic collections over raw (untyped) collections
Throw NullPointerException to indicate a prohibited null parameter value
Favor standard Java exceptions over custom exceptions
Principle 2 – Runtime API• Once an API is designed, created and its back-
end implemented, it’s time to find the right run-time as it affects How successful your API strategy will be in terms of service, liability, scale and ability to meet future needs.
• Hybrid support: As more and more businesses are moving to the cloud, so it is important to find runtime that allows to deploy applications both in the cloud as well as on-premise without having to modify anything.
• Scalability, reliability, availability: These “-ilities”, along with performance, are crucial when searching for a solid API runtime. The last thing you want is an unstable runtime that crashes or experiences outages. Choosing the right enterprise grade technology for your API runtime is crucial to the success of your API.
• Strong Orchestration: A successful runtime should provide strong orchestration and orchestration capabilities. The ability to carry out complex back-end orchestration plays a key role in translation between the API layer and back-end implementation.
Principle 3 – API Design Contract• API publishers should offer a way to easily
create well-defined policies and contracts and associate them with the right APIs and consumers.
• API Contracts are crucial for enforcing security and managing SLAs with API consumers.
• In addition, publish API version which helps in lifecycle management and allows API publishers to assess the impact of retiring a version. Example REST API’s
Principle 4 - Monitor API Usage• The ability to monitor API usage over a period of
time and understand usage patterns from both technical and business perspectives is valuable as it helps business owners and technical teams better understand their users and ultimately create a better service.
• You need to see how consumers are using it i.e. which parts of your service are being used.
• With metrics for both overall usage and per consumer usage, businesses can closely monitor API activity and engagement.
Principle 5 - Continuous Improvement• The ability to re-factor your APIs by iterating
through habits 1-6 multiple times allows you to optimize your API over time to improve consumer experience and productivity.
• API is not a static entity – as new use cases are identified and use of your API expands, enhancements and fixes are inevitable.
Principle 6 -Socialize Your APIs• Create a developer portal to establish a
community around your API is important to its success. By making it easy for users to follow your API, download documentation and ask questions, API publishers can engage with API consumers on an ongoing basis.
• Example create a developer portal for company-wide REST services and document it using Swagger
APIs Are Everywhere
Value of Great API’s• Is a Product • Help Grow a Eco-System of employees, customers
and Partners• Evolve in a way that are mutually beneficial• Encourage Adoption• Ease Of Use• Great APIs aren’t difficult to develop – if you design for your users and the business processes– if you make it easy for developers to find and consume
your API, and – you actively manage your API developer community as
an extension of your business.
Pitfalls of a mediocre APIs• Doesn’t engage Stake-holders• limited adoption by developers and ultimately, a
failure to meet business objectives• Starts with implementation first• Design of API is dictated by the constraints of
internal systems or processes.• Too often APIs are modeled after the design of the
backend services or applications they expose instead of the use case they fulfill. This results in poor performance of the client application, poor user experience, and ultimately, poor adoption.
THANK YOU
Q & A