Discover the World of API Knowledge

Our extensive collection of articles unveils the secrets behind APIs and provides a deep insight into their significance and functionality. Explore the facets of APIs, from their basic operations to innovative applications in various fields.

Latest Articles

API
API Definition

What is an API Definition? The API definition describes the structure and behavior of an API. It specifies which endpoints are available, which requests and responses are expected and which authentication methods must be used. A clearly defined API facilitates implementation and integration into existing systems, improves security and promotes code reusability. An API (Application Programming Interface) is an interface that allows different software applications to communicate with each other. APIs are a central component of modern software development and are used in numerous areas, including payment services, social media integrations and cloud computing. Different API Definitions and Their Use Cases APIs can be distinguished not only by their architecture, but also by the standards used for the definition and documentation of their interfaces. The choice of an API definition influences how developers design, document and implement APIs. Among the best-known standards are OpenAPI Specification (OAS), Swagger 2.0, RAML (RESTful API Modeling Language) and AsyncAPI. OpenAPI Specification (OAS) is currently the most widely used standard for describing RESTful APIs. It enables a machine-readable specification that can be used as a basis for generating code, documentation and tests. OAS facilitates API development by providing a consistent and comprehensible structure for the API definition. Swagger 2.0 was the predecessor of OAS and significantly contributed to the spread of standardized API definitions. With Swagger, developers can create interactive API documentation and test APIs directly. Although OAS is now the official standard, Swagger 2.0 is still used in many existing systems. RAML (RESTful API Modeling Language) is an alternative method for defining RESTful APIs. In contrast to OAS, RAML places a stronger focus on the reusability of API components and offers a clear, human-readable syntax. Developers often use RAML to design APIs in a structured manner before they are implemented. AsyncAPI is specifically designed for asynchronous APIs that are based on event-driven architectures. This standard is used especially for message queues, IoT platforms and microservices. AsyncAPI allows developers to define and document complex real-time communication, thereby enabling applications to be designed efficiently and in a scalable way. Important Components of an API Definition An API consists of several fundamental components that determine its functionality and enable interaction between systems. In this context, endpoints, requests and responses as well as authentication play a crucial role. Endpoints Endpoints are the specific access points of an API through which external applications can access the provided functions. They consist of a URL and define which data is available and how it can be retrieved or manipulated. For example, an endpoint for user management could be accessible at /api/users in order to retrieve or update user information. Requests and Responses Communication between client and server takes place via requests and responses. A client sends a request to an API endpoint, which typically includes an HTTP verb such as GET, POST, PUT or DELETE. The server processes the request and returns a response, which is usually in JSON or XML format. A successful request delivers an appropriate status code (e.g., 200 OK), whereas erroneous requests generate error codes such as 400 Bad Request or 404 Not Found. Business Types and Components In the modeling of API definitions, business objects play a central role. These are often defined by Business Types and Components in order to create reusable and consistent data structures. Business Types are abstracted data types that represent frequently used entities within a system. Examples are User'', Order'' or ``Invoice''. These types help to maintain a consistent structure across different endpoints. Components are reusable API building blocks that are used in definitions such as OpenAPI. They include, for example, schema definitions for data objects, security mechanisms and parameters. By using components, API specifications can be made modular and maintenance-friendly. Best Practices for Modeling an API Definition A well-structured API definition is crucial for efficient development and long-term maintainability. The following best practices help to design APIs that are consistent, comprehensible and extensible. Best Practices for Endpoints The following recommendations help to structure API endpoints clearly, enable efficient communication and ensure uniform usage. Ensure consistent naming: Endpoints should be named clearly, predictably and uniformly. For example, the resource for users should be accessible at /api/users instead of using unclear or different designations such as /api/getUsers or /api/userList. Implement versioning: An API should use versioning from the beginning in order to manage future changes cleanly. For example, /api/v1/users can be used for the first version of the API, while later iterations can run under /api/v2/users without interrupting existing integrations. Use HTTP methods correctly: Using the correct HTTP methods facilitates understanding and usage of the API. GET should be used for retrieving data, POST for creating new resources, PUT for updating and DELETE for removing data. Do not create unnecessary endpoints: Each endpoint should serve a clear function. Instead of creating a new endpoint for every single action (/api/getUsers, /api/updateUser, /api/removeUser), a generic structure should be used that consolidates CRUD operations (GET /api/users, PUT /api/users/{id}, DELETE /api/users/{id}). Offer filtering and pagination: In order to increase efficiency and make large data sets more manageable, endpoints should support options for filtering (/api/users?role=admin) and pagination (/api/users?page=1&limit=20). Best Practices for Requests and Responses The following recommendations help to structure API endpoints clearly, enable efficient communication and ensure uniform usage. Use status codes correctly: Every API should use standardized HTTP status codes for its responses in order to ensure an unambiguous interpretation. For example, 200 OK signals that the request was successful, whereas 201 Created confirms a newly created resource. Erroneous requests should be clearly identifiable by means of informative status codes such as 400 Bad Request (invalid input) or 404 Not Found (non-existent resource). Use uniform and well-structured data formats: JSON is the preferred format for modern APIs because it is easily readable and can be processed efficiently. A consistent schema should be maintained in order to make the structure understandable. For example, an API for users should always deliver the same JSON format: { "id": 1, "name": "Max Mustermann", "email": "max@example.com" } Provide detailed error messages: Instead of returning merely a generic 400 Bad Request error, the API should inform the client exactly why a request has failed. For example: { "error": "Invalid email format", "field": "email", "suggestion": "Please provide a valid email address." } This makes it easier for developers to debug errors and improves the user experience. Enable pagination and limitation of large data sets: APIs that return large data sets should implement mechanisms for pagination and filtering. For example, an API could support the following query: GET /users?page=2&limit=20 This ensures that the response does not become unnecessarily large and that the server is not overloaded. Use caching to improve performance: Frequently used data should be cached to reduce unnecessary API requests. By setting cache-control headers, the server can inform the client how long a response may be cached: Cache-Control: max-age=3600, public This improves loading times and reduces server load. Best Practices for Business Types and Components The following recommendations help to structure API endpoints clearly, enable efficient communication and ensure uniform usage. Uniform and comprehensible naming: Names for Business Types should be clear, descriptive and consistent. Instead of cryptic or abbreviated designations such as CustOrd1, a comprehensible notation such as CustomerOrder should be used. This facilitates readability and reduces misunderstandings, especially in larger development teams or when integrating with other systems. Ensure reusability: An API should be designed in such a way that its components can be used multiple times, in order to avoid redundancies and improve maintainability. For example, an Address schema can be used equally for users, companies and suppliers. Instead of creating separate address models for each entity (UserAddress, CompanyAddress), a generic Address schema should be implemented that can be used flexibly in different contexts. This not only facilitates the maintenance of the API, but also reduces inconsistencies in data processing. Use standardized types: In order to ensure a consistent and interoperable API, standardized data types should be used. For example, UUIDs (Universally Unique Identifiers) are ideal for unique identifiers because they ensure that each entry receives a unique and unpredictable ID. For date and time indications, the ISO 8601 standard (YYYY-MM-DDTHH:MM:SSZ) should be used, as it is internationally understandable and compatible with most programming languages. This prevents interpretation errors, especially in systems that operate with different time zones. Likewise, ISO 4217 for currency codes and ISO 3166-1 alpha-2 for country codes can be used to ensure uniformity. Best Practices for Authentication and Authorization The following recommendations help to structure API endpoints clearly, enable efficient communication and ensure uniform usage. Use OAuth 2.0 for secure authentication: OAuth 2.0 is a widely used and secure standard for authorization that enables flexible access control. It supports various grant types, including the Authorization Code Flow for web applications and the Client Credentials Flow for server-side applications. By using OAuth 2.0, APIs can ensure that only authorized clients gain access to protected resources. A frequently used extension protocol is OpenID Connect (OIDC), which enables identity verification with standardized user information.. Use JWTs to avoid server-side sessions: JSON Web Tokens (JWTs) enable secure and efficient authentication without the need for server-side sessions. A JWT consists of three parts: header, payload and signature, which together provide an encrypted and signed method for verifying a user’s identity. JWTs are particularly useful for scalable applications because they function as stateless tokens and reduce the overhead of centralized session management. However, they should always be provided with short expiration times (the exp claim) and stored securely, for example in HTTP-only cookies, to avoid attacks through token theft. Never pass tokens in URLs, but set them in the Authorization header: Transmitting tokens in URLs carries significant security risks because URLs can be stored in browser histories, server logs and referrer headers. Instead, tokens should always be transmitted securely in the Authorization header: Authorization: Bearer <token> This method ensures that tokens are not inadvertently exposed or intercepted by attackers. In addition, the API should be configured so that it communicates only over secure HTTPS connections to prevent man-in-the-middle attacks. Conclusion These API definitions play a crucial role in modern software development. They not only enable consistent documentation and development, but also seamless integration into various tools and frameworks. The choice of the right standard depends on the specific requirements of the respective project.

API
OpenAPI Specification (OAS)

The now high level of networking and digitization in business, industry, administration and the private sector also requires increasingly high-quality services and requirements for software structures. Data-based ecosystems and platforms now use complex and powerful API interfaces to meet business requirements. Open interfaces for the versatile applicability of data and information represent a central key position here. The more complex an interface must be designed, the more important an open and defined structure is. This is then documented with an appropriate description language. Open API provides developers with a modern and powerful API description language for their projects. Based on Swagger’s open source tools, which are already very successfully established on the market, the new Open-API project was founded in 2015 under the leadership of the Linux Foundation from the Open-API Initiative. This initiative currently has 26 active members, many of whom are big players. Here, renowned companies such as Microsoft, Google, SAP, Paypal, Adobe, Smartbear or MuleSoft can be found. This ensures a comprehensive compatibility and structure of the services provided and published. Version 3 has been available since 2017 for project planning and implementation of powerful APIs. One of the biggest advantages of Open-API is the comprehensive language support for Java, JScript, .Net, Ruby, Scala or Gitlab. These are all based on the formats of JSON or YAML 1.2 and thus provide very high compatibility. Further innovations can be found in the finally adapted and extended support of the JSON schema. In addition, innovations and restructurings have been introduced in the areas of security and hosts. The reuse of components was solved in a particularly convenient way. HTTP headers, requests, responses, parameters, callbacks, links, object schemes and examples can now be stored in a separate area. The core elements of Open API The requirements should already be clearly defined during the planning of an API. Here it is particularly important to deal with the core elements of functionality and later documentation. Every user of an API must be able to access the information of the used parameters, endpoints, return values and safety factors. This is the only way to ensure optimum and efficient use of the interface. There are various groups of core data in the Open API, which we will discuss in more detail below. Documentation In order to be able to map the individual components of the API clearly, external documents are usually also made available to explain the API functions, parameters, endpoints or details of the website such as terms of use etc. In the area Docs corresponding references to these documents and schemata can be inserted. The following example shows the format to be used: externalDocs: description: Learn more about user operations provided by this API. url: http://api.api-portal.io/docs/user-operations/ A short description of the document contents is inserted after the parameter description:. The url: parameter also provides the link to the document resource. Details Within the section Details all basic information about the API is provided. This information is also valid API-wide. This section contains important parameters that should be entered. The following source code excerpt describes the individual values in the required format: info: title: Sample API description: Optional multiline or single-line description in [CommonMark](http://commonmark.org/help/) or HTML. version: 0.1.9 servers: - url: http://api.api-portal.io/v1 description: Optional server description, e.g. Main (production) server - url: http://staging.api-portal.io/v2 description: Optional server description, e.g. Internal staging server for testing The first section info: describes the function of the API in short words. The parameter title: names a freely selectable title for the API, the second parameter description: names the core function of this API and may also contain external links to a reference source. The version: section speaks for itself and maps the currently used API version. This information is especially valuable for different revisions of an API. The servers: section now lists the active host of this API. In the url: parameter, each base path used is listed individually and in detail. With the parameter description: follows a short description of the path. Security The Security section describes all authentication methods used and permitted in the API. For each entry, there are various parameters that refer to the use of the schema. The following source code excerpt shows an example of the correct use: components: securitySchemes: BasicAuth: type: http scheme: basic BearerAuth: type: http scheme: bearer ApiKeyAuth: type: apiKey in: header name: X-API-Key OpenID: type: openIdConnect openIdConnectUrl: https://example.com/.well-known/openid-configuration OAuth2: type: oauth2 flows: authorizationCode: authorizationUrl: https://example.com/oauth/authorize tokenUrl: https://example.com/oauth/token scopes: read: Grants read access write: Grants write access admin: Grants access to admin operations In addition to Basic and Bearer-Auth, other schemas can also be specified. With OAuth2, several details are assigned to the URLs and scopes. The access level can then be specifically named here. As soon as the security rule is entered in the root, it is valid for the entire API. Here is a possible scenario in which the security schema OAuth2 only allows read and write access: security: - ApiKeyAuth: [] - OAuth2: - read - write Furthermore, a distinction is also made between the possible authentication methods with regard to the individual resource operations such as reading and writing. In the following example, the OAuth2 method with admin rights is defined specifically for read access to invoice information: paths: /billing_info: get: summary: Gets the account billing info security: - OAuth2: [admin] # Use OAuth with a different scope responses: '200': description: OK Resources Typically, an API uses a wide variety of resources such as files, forms, or other information. To access this data, the HTTP protocol also defines various request and access methods. This signals to a browser, for example, how to deal with the request. Basically there are 4 standard request methods which can be applied to resources. In the following we present these together with a simple example parameterization: GET - With this HTTP method a resource can be read. Please note that a GET method must not change any inventory data on the server. To find and read a specific entry using the identifier, use the following query method: GET /user/{userID} POST - The POST method is usually used to create a new resource whose URI is not yet known to the system. This is the default method for adding a new resource: POST /user 2. PUT - Use this method to edit or change an existing and known resource. This method is mainly used for updating data: PUT /user 2 DELETE - To delete a known and existing resource, use the DELETE method with the identifier. Please note the resource rights, if the method call with the user rights can be executed at all: DELETE /user/{userID} The corresponding method parameters are specified in detail for each individual resource. The following source code shows an example of the search for a user data record. Status code 200 for the successful query and codes 400 and 404 for error messages are defined as return values: paths: /user/{userId}: get: summary: Returns a user by ID. parameters: - name: userId in: path required: true description: The ID of the user to return. schema: type: integer format: int64 minimum: 1 responses: '200': description: A user object. content: application/json: schema: type: object properties: id: type: integer format: int64 example: 4 name: type: string example: Jessica Smith '400': description: The specified user ID is invalid (not a number). '404': description: A user with the specified ID was not found. default: description: Unexpected error Types In the type definitions of the API all used business objects are described in detail with ID and the properties together with value ranges. Descriptive categories are also used to better classify the object. In the following example, you create a reusable object in the component container with all relevant properties, data types and scopes: components: schemas: Category: type: object properties: id: type: integer format: int64 name: type: string Errors One or more status messages should also be defined for each API request. This applies in particular to errors that occur. The more precisely you assign error codes to each API call, the easier it will be to handle the interface. Under the parameter responses you define all error codes that can be returned. Use the parameter description: to document the type of error message as a reference to the source. Advantages and disadvantages of Open API With the new version 3 of the Open API many bugs have been fixed and long overdue new features have been added. The large community and the broad application by the Swagger tools will inspire a fast standardization. The participation of many big players and the lack of a vendor lock will also provide a powerful boost. Many well-known frameworks now also rely on broad Open API support. Above all, the broad restructuring in user administration and in the header area makes handling much easier. A further clear advantage are the now reusable objects via their own section. But where there is light, there is usually also shade to be found. Currently, only a few tools and development environments are specifically designed for Open API. Also the reuse of code snippets is not yet available and there are certain incompatibilities between the versions. However, these shortcomings will certainly be eliminated in the foreseeable future. Conclusion The markup language Open API has many advantages and therefore similarities with RAML. However, due to the relatively good selection of code generators and the many tools in the ecosystem, many project managers will prefer Open API. If you attach great importance to extensive language support, this is the right place for you. In the medium term, Open API will probably become the new standard in API documentation, which the already large community will certainly welcome.

Trainings

Sign up and become the API expert in your industry!

Sign Up