What exactly IS an API? An application programming interface (API) is a computing interface that defines interactions between multiple software intermediaries. It defines the kinds of calls or requests that can be made, how to make them, the data formats that should be used, the conventions to follow, etc. It can also provide extension mechanisms so that users can extend existing functionality in various ways and to varying degrees. In basic terms, APIs are a set of functions and procedures that allow for the creation of applications that access data and features of other applications, services, or operating systems.
Why do we need an API? Imagine the following scenario: You wants to access another app’s data or functionality. For example, perhaps you want to access posts from reddit regarding some random topic. You could email reddit and ask for a spreadsheet of all these posts. But then you’d have to find a way to import that spreadsheet into your application. Even if you stored them in a database, as we have been, the data would become outdated very quickly. It would be impossible to keep it up to date. It would be better and simpler for reddit to just provide you a way to query their application to get that data so that you can view or use it in your application. It would stay up to date automatically that way. So, the API provides access to data, so this data can be included in different applications.
What are the Magento web APIs? Magento API is a type of framework that offers developers and integrators a good method to maximize web services which communicate well with the Magneto system. Amongst the primary features are supports for SOAP (Simple Object Access Protocol) and REST (Representation State Transfer).
There are 3 types of authentication: • Third-party applications authenticate with OAuth 1.0a. • Mobile applications authenticate using tokens. • Administrators and customers are authenticated with login credentials.
Each account and integration serves as assigned sources which they can access. The API framework monitors the calls to check if the account is authorized to do the request. Any Magento or third-party service can be configured as a web API with a few lines of xml. To configure a web API, you define XML elements and attributes in a webapi.xml configuration file. If a service is not defined in a configuration file, it will not be exposed at all. The framework is based on the CRUD (create, read, update, delete) & search model. The system does not currently support webhooks.
The Magento APIs could be used to execute tasks like: • Create a shopping app. This can be a traditional app that a user downloads on a mobile device. You could also create an app that an employee uses on a showroom floor to help customers make purchases. • Integrate with CRM (Customer Relationship Management) or ERP (Enterprise Resource Planning) backend systems, such as Salesforce or Xero. • Integrate with a CMS (Content Management System). At present, content tagging is not supported. • Create JavaScript widgets in the Magento storefront or on the Admin panel. The widget makes AJAX calls to access services.
How do I get started? You must register a web service on Magento Admin. Use the following general steps to set up Magento to enable web services. 1. If you are using token-based authentication, create a web services user on Magento Admin by selecting System > Permission > All Users > Add New User. (If you are using session-based or OAuth authentication, you do not need to create the new user in the Admin.) 2. Create a new integration on Magento Admin. To create an integration, click System > Extensions > Integration > Add New Integration. Be sure to restrict which resources the integration can access. 3. Use a REST or SOAP client to configure authentication.
What is REST API The Magento 2 REST API identifies various functions which can be used to perform requests and receive responses. A developer can perform these interactions by using the HTTP potocol. The caller leads to an HTTP request which includes the below elements: • An HTTP header which provides not only authentication but also other instructions • A verb which is the action against the endpoint, it can be GET, POST, PUT, and DELETE. • An endpoint is a Uniform Resource Indicator (URI). This endpoint identifies the server, the web service, and also the resource which is acted on. • The call payload includes set of input parameters and attributes which you supply with the request.
A response payload and an HTTP status code will be returned
Overview The following table and the sections that follow the table describe web API call elements:
HTTP headers Below is the table which describes three HTTP headers in your web API calls:
Authorization
Bearer
Authorization: Bearer <TOKEN>
<TOKEN>
Accept
JSON
Accept: application/<FORMAT>
<FORMAT>
XML
Content-Type
Content-Type: application/<FORMAT>
HTTP verb Specify one of these HTTP verbs in the request: • GET. Requests transfer of a current representation of the target resource. If you omit the verb, GET is the default. • PUT. Requests that the state of the target resource be created or replaced with the state defined by the representation enclosed in the request message payload. • POST. Requests that the origin server accept the representation enclosed in the request as data to be processed by the target resource. • DELETE. Requests that the origin server delete the target resource.
Endpoint An endpoint is a combination of the server that fulfills a request, the web service, the store code, the resource against which the request is being made, and any template parameters. For example, in the http://magento.ll/index.php/rest/default/V1/customerGroups/:id endpoint, the server is magento.ll/index.php/, the web service is rest, the resource is /V1/customerGroups, and the template parameter is id. A store code can have one of the following values. • The store’s assigned store code. • default. This is the default value when no store code is provided. • All This value only applies to endpoints defined in the CMS and Product modules. If this value is specified, the API call affects all of the merchant’s stores.
Call payload This element is a set of input parameters and attributes which are supplied with the request. Both required and optional inputs are included in API operations. Input parameters are specified in the URI. For instance, in the URI GET/V1/customers/:customerId, the customerId template parameter must be specified. Input attributes are specified in a JSON- or XML-formatted request body. For example, in the POST /V1/customers call, a request body must be specified like this:
{ "customer": { "email": "user@example.com", "firstname": "John", "lastname": "Doe" }, "addresses": [ { "defaultShipping": true, "defaultBilling": true, "firstname": "John", "lastname": "Doe", "region": { "regionCode": "CA", "region": "California", "regionId": 12 }, "postcode": "90001", "street": ["Zoe Ave"], "city": "Los Angeles", "telephone": "555-000-00-00", "countryId": "US" } ] }
This includes a customer object which has customer email, first name, last name, and address information. This information is used to populate the new customer account.
How to call a request
This example shows you how to construct a REST web API call to create an account.
createAccount
<route url="/V1/customers" method="POST"> <service class="Magento\Customer\Api\AccountManagementInterface" method="createAccount"/> <resources> <resource ref="anonymous"/> </resources> </route>
3. Use the method and url values on the route element to construct the URI. In this example, the URI is POST /V1/customers.
method
url
route
/V1/customers
4.Use the class attribute on the service element to identify the service interface. In this example, the service interface is the AccountManagementInterface PHP file.
class
service
AccountManagementInterface
Open the AccountManagementInterface.php file and find the createAccount method, as follows:
public function createAccount( \Magento\Customer\Api\Data\CustomerInterface $customer, $password = null, $redirectUrl = '' )
The createAccount call requires a customer data object. The password and redirectUrl values are optional. The default password value is null and the default redirectUrl value is blank.
customer
password
redirectUrl
null
5. To pass the customer data object in the POST call payload, specify JSON or XML request body on the call.
REST responses
Each web API call returns a HTTP status code and a response payload. When an error occurs, the response body also returns an error message.
HTTP status codes
Each web API call returns an HTTP status code that reflects the result of a request:
Magento_Service_Exception
Response payload
POST, PUT, and GET web API calls return a response payload. This payload is a JSON- or XML-formatted response body. The Accept: application/<FORMAT> header in the request determines the format of the response body, where FORMAT is either json or xml.
FORMAT
json
xml
A successful DELETE call returns true. An unsuccessful DELETE call returns a payload similar to the other calls.
true
The response payload depends on the call. For example, a GET /V1/customers/:customerId call returns the following payload:
GET /V1/customers/:customerId
{ "customers": { "customer": { "email": "user@example.com", "firstname": "John", "lastname": "Doe" }, "addresses": [ { "defaultShipping": true, "defaultBilling": true, "firstname": "John", "lastname": "Doe", "region": { "regionCode": "CA", "region": "California", "regionId": 12 }, "postcode": "90001", "street": ["Zoe Ave"], "city": "Los Angeles", "telephone": "555-000-00-00", "countryId": "US" } ] } }
This JSON-formatted response body includes a customer object with the customer email, first name, and last name, and customer address information. The information in this response body shows account information for the specified customer.
Error format When an error occurs, the response body contains an error code, error message, and optional parameters.
code
message
parameters
As an example, Magento returns a code of 400 and the following message when an invalid sku value is specified in the call PUT V1/products/:sku.
400
sku
PUT V1/products/:sku
{ "message": "Invalid product data: %1", "parameters": [ "Invalid attribute set entity type" ] }
Conclusion Above I have just provided you the information about REST Apis and how a request can be constructed. If you have further questions or new ideas, feel free to leave a comment below.
References
https://devdocs.magento.com
https://developers.google.com
https://www.mageplaza.com
https://en.wikipedia.org
Du musst angemeldet sein, um einen Kommentar abzugeben.