> ## Documentation Index
> Fetch the complete documentation index at: https://docs.apinizer.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Script-2-API Usage

> Enables using Script-2-API in the Apinizer Platform. You can create REST APIs by creating methods with JavaScript or Groovy script languages, and use, update, or delete message sections with custom-defined variables in code.

Script-2-API enables you to create REST APIs by creating methods with JavaScript or Groovy script languages without needing any code editor.

You can use, update, or delete message sections in code with custom-defined variables.

This content explains, in order, defining Script-2-API for a REST API that manages email operations, creating the sendMail method to send emails, and creating, deploying, and testing the REST API as an API Proxy.

## 1. Creating Script-2-API

REST API definition is made by easily entering the general information of the API on the Script-2-API screen.

<img src="https://mintcdn.com/apinizer/vLTzl9yHOLX7IruV/images/tutorials/api-olusturucu-senaryolari/script-2-api/01-script2api-settings.png?fit=max&auto=format&n=vLTzl9yHOLX7IruV&q=85&s=615f5d9df41537317cbdd85459842e91" alt="Script-2-API Creation" width="800" data-path="images/tutorials/api-olusturucu-senaryolari/script-2-api/01-script2api-settings.png" />

### 1.1. Creating the /sendMail Method

In the image below, the **/sendMail** method is created in Groovy to send emails by retrieving email information from the request message body.

To add a method, click the **Add** button, enter the method information, and press the **Save** button.

<img src="https://mintcdn.com/apinizer/vLTzl9yHOLX7IruV/images/tutorials/api-olusturucu-senaryolari/script-2-api/02-sendmail-method-creation.png?fit=max&auto=format&n=vLTzl9yHOLX7IruV&q=85&s=523e8541aecec96bdc1f12e3687abd50" alt="/sendMail Method Creation" width="800" data-path="images/tutorials/api-olusturucu-senaryolari/script-2-api/02-sendmail-method-creation.png" />

<Note>
  You can test the script code by clicking the **Try It** button.
</Note>

Groovy code;

```groovy theme={null}
import javax.mail.*
import javax.mail.internet.*
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

try {
    requestHeaderMapFromClient.put('statusCode', 0);
    def jsonSlurper = new JsonSlurper()
    def jsonMessage = jsonSlurper.parseText(requestBodyTextFromClient)
    
    String from = jsonMessage.sender;
    if (from.equals("bilgi.apinizer")){
        from="info@apinizer.com";
    } else if(from.equals("apinizer.hata")){
        from="warning@apinizer.com";
    } else {
        statusCode=400;
        requestErrorMessageFromClient = JsonOutput.toJson([
            isTheOperationSuccessful: false, 
            errorMessage: 'Hatalı gönderen bilgisi', 
            errorCode:'01-ERR-02'
        ])
        return;
    }
    
    String to=jsonMessage.reciever;
    String cc=jsonMessage.recieverInformation;
    String bcc=jsonMessage.recieverInformation;
    
    if(!to?.trim() && !cc?.trim() && !bcc?.trim()){
        requestErrorMessageFromClient = JsonOutput.toJson([
            isTheOperationSuccessful: false, 
            errorMessage: 'En az bir alıcı eklenmeli', 
            errorCode:'01-ERR-03'
        ])
        statusCode=400;
        return;
    }
    
    String subject=jsonMessage.subject;
    if(subject?.trim()){
        subject=""
    }
    
    String content=jsonMessage.content;
    if(content?.trim()){
        content=""
    }
    
    String mimeType=jsonMessage.contentType;
    if(mimeType?.trim()){
        mimeType="text/html;charset=utf-8"
    }
    
    // Init constants of sender email account.
    String email = "apinizer.hata"
    String password = ""
    String host = "mail.apinizer.com"
    String port = "25" // "465" "587"
    
    // Set up properties.
    Properties props = System.getProperties()
    props.put("mail.smtp.user", email)
    props.put("mail.smtp.host", host)
    props.put("mail.smtp.port", port)
    props.put("mail.smtp.auth", "false")
    props.put("mail.smtp.starttls.enable", "false")
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory")
    props.put("mail.smtp.ssl.trust", host) // Change host to "*" if you want to trust all host.
    
    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(email, password);
        }
    });
    
    // Set up message.
    MimeMessage message = new MimeMessage(session)
    message.setFrom(new InternetAddress(from))
    if(to?.trim()){
        message.addRecipients(Message.RecipientType.TO, new InternetAddress(to))
    }
    if(cc?.trim()){
        message.addRecipients(Message.RecipientType.CC, new InternetAddress(cc))
    }
    if(bcc?.trim()){
        message.addRecipients(Message.RecipientType.BCC, new InternetAddress(bcc))
    }
    message.setSubject(subject)
    message.setContent(content, mimeType)
    
    try {
        // Send mail.
        Transport.send(message)
    } catch (MessagingException e) {
        e.printStackTrace();
        statusCode=500;
        responseErrorMessageToClient = JsonOutput.toJson([
            isTheOperationSuccessful: false, 
            errorMessage: 'Error occurred while sending mail:' + e.getMessage(), 
            errorCode:'01-ERR-04'
        ])
        return;
    }
    
    statusCode=200;
    responseBodyTextToClient = JsonOutput.toJson([
        isTheOperationSuccessful: true, 
        errorMessage: '', 
        errorCode:''
    ])
} catch (MessagingException e) {
    e.printStackTrace();
    statusCode=500;
    responseErrorMessageToClient = JsonOutput.toJson([
        isTheOperationSuccessful: false, 
        errorMessage: 'Error occurred while sending mail:' + e.getMessage(), 
        errorCode:'01-ERR-05'
    ])
    return;
}
```

When sending an email, the request body should contain the following JSON body;

```json theme={null}
{
 "sender":"info@apinizer.com",
 "reciever":"user@apinizer.com",
 "recieverInformation":null,
 "secretReceivers":null,
 "subject":"test",
 "content":"test",
 "contentType":"text/html;charset=utf-8"
}
```

When a successful response is returned, you encounter a message template example in the following template;

```json theme={null}
{
 "isTheOperationSuccessful":true,
 "errorMessage":"",
 "errorCode":""
}
```

When an error response is returned, you encounter a message template example in the following template;

```
Script Error: {
 "isTheOperationSuccessful":false,
 "errorMessage":"Error occurred while sending mail:Invalid Addresses",
 "errorCode":"01-ERR-04"
}
```

## 2. Viewing API Definition Documents

Click the **Show Specs** link to access the API definition files for Mail API.

<img src="https://mintcdn.com/apinizer/vLTzl9yHOLX7IruV/images/tutorials/api-olusturucu-senaryolari/script-2-api/03-show-specs.png?fit=max&auto=format&n=vLTzl9yHOLX7IruV&q=85&s=88ea014dd5c4f36df916dd499be4ef73" alt="Show Specs" width="1000" data-path="images/tutorials/api-olusturucu-senaryolari/script-2-api/03-show-specs.png" />

**The image below shows the Spec Information dialog:**

<img src="https://mintcdn.com/apinizer/vLTzl9yHOLX7IruV/images/tutorials/api-olusturucu-senaryolari/script-2-api/04-spec-info.png?fit=max&auto=format&n=vLTzl9yHOLX7IruV&q=85&s=c7c5bfc3f1cb8b4e9b5c15c30bede706" alt="Spec Information" width="600" data-path="images/tutorials/api-olusturucu-senaryolari/script-2-api/04-spec-info.png" />

## 3. Creating API Proxy

You can instantly create an API Proxy by clicking the **Create API Proxy** button from the Script-2-API screen.

<img src="https://mintcdn.com/apinizer/vLTzl9yHOLX7IruV/images/tutorials/api-olusturucu-senaryolari/script-2-api/05-create-api-proxy.png?fit=max&auto=format&n=vLTzl9yHOLX7IruV&q=85&s=38b99b39bf12b088eb7d049ad852909c" alt="Create API Proxy" width="1000" data-path="images/tutorials/api-olusturucu-senaryolari/script-2-api/05-create-api-proxy.png" />

When creating the API Proxy, fill in the input fields shown in the image below and click the **Save** button.

<img src="https://mintcdn.com/apinizer/vLTzl9yHOLX7IruV/images/tutorials/api-olusturucu-senaryolari/script-2-api/06-api-proxy-creation-form.png?fit=max&auto=format&n=vLTzl9yHOLX7IruV&q=85&s=b65043ca3fa6a528f30f7f5bb4b6abfe" alt="API Proxy Creation Form" width="600" data-path="images/tutorials/api-olusturucu-senaryolari/script-2-api/06-api-proxy-creation-form.png" />

### 3.1 Deploying the API Proxy

Mail API Proxy can be quickly deployed to a defined environment and made available for client consumption.

This operation can be managed through the dialog opened by the **Deploy** button on the API Proxy screen.

<img src="https://mintcdn.com/apinizer/vLTzl9yHOLX7IruV/images/tutorials/api-olusturucu-senaryolari/script-2-api/07-deploy-dialog.png?fit=max&auto=format&n=vLTzl9yHOLX7IruV&q=85&s=a56c0bbe42399638768d4ce365b3f7f8" alt="Deploy Dialog" width="1000" data-path="images/tutorials/api-olusturucu-senaryolari/script-2-api/07-deploy-dialog.png" />

This operation can also be managed from the Script-2-API screen via the **Manage API Proxies** link.

<img src="https://mintcdn.com/apinizer/vLTzl9yHOLX7IruV/images/tutorials/api-olusturucu-senaryolari/script-2-api/08-manage-api-proxies.png?fit=max&auto=format&n=vLTzl9yHOLX7IruV&q=85&s=5b90ff32943f6c44ee7c726a2104687f" alt="Manage API Proxies" width="1000" data-path="images/tutorials/api-olusturucu-senaryolari/script-2-api/08-manage-api-proxies.png" />

## 4. Testing

The image below shows testing the **/sendMail** method from the API Proxy page;

<img src="https://mintcdn.com/apinizer/vLTzl9yHOLX7IruV/images/tutorials/api-olusturucu-senaryolari/script-2-api/09-test-result.png?fit=max&auto=format&n=vLTzl9yHOLX7IruV&q=85&s=c6104ace42399b3acdafe277b43573ad" alt="Test Result" width="800" data-path="images/tutorials/api-olusturucu-senaryolari/script-2-api/09-test-result.png" />
