# The Answer in Code (g.res)

> Shape the answer of an API in your code with g.res of API Maker - its output, status code, errors, warnings, data shared between hooks, and the content type (JSON, HTML, text, XML, YAML, bytes) - in eight languages.

Source: https://docs.apimaker.dev/v4/examples/res/res.html

> **The code in every language**
>
> Each example is the inside of `main`, written in every [language](https://docs.apimaker.dev/v4/docs/languages/index.html) API Maker runs : pick yours in the tabs, and every page shows it from then on. The types a call takes (`GetAll`, `DeepItem`…) are those of `am` : `from am import GetAll` in Python, `use am::GetAll;` in Rust, `import am.GetAll;` in Java and Kotlin ; PHP and C# have them without an import, Go names them `am.GetAll`.

Custom APIs and hooks shape the answer of the request through `g.res`.

## Output

**TypeScript**

```typescript
g.res.output = { hello: 'world' };
```

**Python**

```python
g.res.output = {'hello': 'world'}
```

**PHP**

```php
$g->res->output = ['hello' => 'world'];
```

**C#**

```csharp
g.Res.Output = new JsonObject { ["hello"] = "world" };
```

**Go**

```go
g.Res.SetOutput(am.M{"hello": "world"})
```

**Rust**

```rust
g.res.set_output(json!({ "hello": "world" }));
```

**Java**

```java
g.res.setOutput(Map.of("hello", "world"));
```

**Kotlin**

```kotlin
g.res.output = mapOf("hello" to "world")
```

Response
```json
{
    "success": true,
    "statusCode": 200,
    "data": {
        "hello": "world"
    }
}
```

## Status code

`statusCode` use to set/get status code of the response.

**TypeScript**

```typescript
g.res.statusCode = T.EStatusCode.BAD_REQUEST;
```

**Python**

```python
g.res.status_code = 400  # BAD_REQUEST
```

**PHP**

```php
$g->res->statusCode = 400; // BAD_REQUEST
```

**C#**

```csharp
g.Res.StatusCode = 400; // BAD_REQUEST
```

**Go**

```go
g.Res.SetStatusCode(400) // BAD_REQUEST
```

**Rust**

```rust
g.res.set_status_code(400); // BAD_REQUEST
```

**Java**

```java
g.res.setStatusCode(400); // BAD_REQUEST
```

**Kotlin**

```kotlin
g.res.statusCode = 400 // BAD_REQUEST
```

Response
```json
{
    "success": false,
    "statusCode": 400,
    "data": 400
}
```

All supported status code.
```text
OK = 200,
NO_CONTENT = 204,
CREATED = 201,
BAD_REQUEST = 400,
UNAUTHORIZED = 401,
FORBIDDEN = 403,
RESOURCE_NOT_FOUND = 404,
INTERNAL_SERVER_ERROR = 500
```

## Errors

**TypeScript**

```typescript
g.res.errors = [{ code: 400, message: "Error message here." }];
```

**Python**

```python
g.res.errors = [{'code': 400, 'message': 'Error message here.'}]
```

**PHP**

```php
$g->res->errors = [['code' => 400, 'message' => 'Error message here.']];
```

**C#**

```csharp
g.Res["errors"] = new JsonArray(new JsonObject { ["code"] = 400, ["message"] = "Error message here." });
```

**Go**

```go
g.Res.M["errors"] = []any{am.M{"code": 400, "message": "Error message here."}}
```

**Rust**

```rust
*g.res.errors_mut() = json!([{ "code": 400, "message": "Error message here." }]);
```

**Java**

```java
g.res.setErrors(List.of(new ResponseError(Map.of("code", 400, "message", "Error message here."))));
```

**Kotlin**

```kotlin
g.res.errors = listOf(ResponseError(mapOf("code" to 400, "message" to "Error message here.")))
```

Response
```json
{
    "success": false,
    "statusCode": 400,
    "errors": [
        {
            "code": 400,
            "message": "Error message here."
        }
    ],
    "warnings": []
}
```

## Warnings

**TypeScript**

```typescript
g.res.warnings = [{ code: 401, message: "This is warning!" }];
return { hello: 'v2' };
```

**Python**

```python
g.res.warnings = [{'code': 401, 'message': 'This is warning!'}]
return {'hello': 'v2'}
```

**PHP**

```php
$g->res->warnings = [['code' => 401, 'message' => 'This is warning!']];
return ['hello' => 'v2'];
```

**C#**

```csharp
g.Res["warnings"] = new JsonArray(new JsonObject { ["code"] = 401, ["message"] = "This is warning!" });
return new { hello = "v2" };
```

**Go**

```go
g.Res.M["warnings"] = []any{am.M{"code": 401, "message": "This is warning!"}}
return am.M{"hello": "v2"}, nil
```

**Rust**

```rust
*g.res.warnings_mut() = json!([{ "code": 401, "message": "This is warning!" }]);
Ok(json!({ "hello": "v2" }))
```

**Java**

```java
g.res.setWarnings(List.of(new ResponseError(Map.of("code", 401, "message", "This is warning!"))));
return Map.of("hello", "v2");
```

**Kotlin**

```kotlin
g.res.warnings = listOf(ResponseError(mapOf("code" to 401, "message" to "This is warning!")))
return mapOf("hello" to "v2")
```

Response
```json
{
    "success": true,
    "statusCode": 200,
    "data": {
        "hello": "v2"
    },
    "warnings": [
        {
            "code": 401,
            "message": "This is warning!"
        }
    ]
}
```

## Shared between hooks and code

`g.res.shared` is used to share data between post-hooks, pre-hooks, and code within that API.

**TypeScript**

```typescript
g.res.shared.name = 'Joe';
return g.res.shared.name;
```

**Python**

```python
g.res.shared.name = 'Joe'
return g.res.shared.name
```

**PHP**

```php
$g->res->shared->name = 'Joe';
return $g->res->shared->name;
```

**C#**

```csharp
g.Res.Shared["name"] = "Joe";
return g.Res.Shared.GetString("name");
```

**Go**

```go
g.Res.Shared()["name"] = "Joe"
return g.Res.Shared().String("name"), nil
```

**Rust**

```rust
g.res.shared_mut()["name"] = json!("Joe");
Ok(g.res.shared()["name"].clone())
```

**Java**

```java
g.res.getShared().put("name", "Joe");
return g.res.getShared().getString("name");
```

**Kotlin**

```kotlin
g.res.shared["name"] = "Joe"
return g.res.shared.getString("name")
```

Response
```json
{
    "success": true,
    "statusCode": 200,
    "data": "Joe"
}
```

## Content types

- The user does not need to set the response content type to send JSON as a response.
- If the response content type is not set that means it is application/JSON.

If ContentType is set to below system will return data accordingly.
```text
JSON = 'application/json'
XML = 'text/xml'
YAML = 'text/yaml'
TEXT = 'text/plain'
HTML = 'text/html'
```

> Note: If content type is set and not from above list, then API Maker will consider a text the code returns as base64 encoded. Bytes the code returns (a `Buffer`, `bytes`, `byte[]`, `[]byte`…) are sent as they are, whatever the content type : see OCTET_STREAM below.

### HTML

**TypeScript**

**Content type HTML**

```typescript
g.res.contentType = T.EContentType.HTML;
return "<!DOCTYPE html><html><body><h1>My First Heading </h1><p> My first paragraph.</p></body></html>";
```

**Python**

**Content type HTML**

```python
g.res.content_type = 'text/html'
return '<!DOCTYPE html><html><body><h1>My First Heading </h1><p> My first paragraph.</p></body></html>'
```

**PHP**

**Content type HTML**

```php
$g->res->contentType = 'text/html';
return '<!DOCTYPE html><html><body><h1>My First Heading </h1><p> My first paragraph.</p></body></html>';
```

**C#**

**Content type HTML**

```csharp
g.Res.ContentType = "text/html";
return "<!DOCTYPE html><html><body><h1>My First Heading </h1><p> My first paragraph.</p></body></html>";
```

**Go**

**Content type HTML**

```go
g.Res.SetContentType("text/html")
return "<!DOCTYPE html><html><body><h1>My First Heading </h1><p> My first paragraph.</p></body></html>", nil
```

**Rust**

**Content type HTML**

```rust
g.res.set_content_type("text/html");
Ok(json!("<!DOCTYPE html><html><body><h1>My First Heading </h1><p> My first paragraph.</p></body></html>"))
```

**Java**

**Content type HTML**

```java
g.res.setContentType("text/html");
return "<!DOCTYPE html><html><body><h1>My First Heading </h1><p> My first paragraph.</p></body></html>";
```

**Kotlin**

**Content type HTML**

```kotlin
g.res.contentType = "text/html"
return "<!DOCTYPE html><html><body><h1>My First Heading </h1><p> My first paragraph.</p></body></html>"
```

Response
```html
<!DOCTYPE html><html><body><h1>My First Heading </h1><p> My first paragraph.</p></body></html>
```

### JSON

**TypeScript**

**Content type JSON**

```typescript
g.res.contentType = T.EContentType.JSON;
g.res.errors = [{ code: 401, message: "This is error" }];
g.res.statusCode = 555;
return "World";
```

**Python**

**Content type JSON**

```python
g.res.content_type = 'application/json'
g.res.errors = [{'code': 401, 'message': 'This is error'}]
g.res.status_code = 555
return 'World'
```

**PHP**

**Content type JSON**

```php
$g->res->contentType = 'application/json';
$g->res->errors = [['code' => 401, 'message' => 'This is error']];
$g->res->statusCode = 555;
return 'World';
```

**C#**

**Content type JSON**

```csharp
g.Res.ContentType = "application/json";
g.Res["errors"] = new JsonArray(new JsonObject { ["code"] = 401, ["message"] = "This is error" });
g.Res.StatusCode = 555;
return "World";
```

**Go**

**Content type JSON**

```go
g.Res.SetContentType("application/json")
g.Res.M["errors"] = []any{am.M{"code": 401, "message": "This is error"}}
g.Res.SetStatusCode(555)
return "World", nil
```

**Rust**

**Content type JSON**

```rust
g.res.set_content_type("application/json");
*g.res.errors_mut() = json!([{ "code": 401, "message": "This is error" }]);
g.res.set_status_code(555);
Ok(json!("World"))
```

**Java**

**Content type JSON**

```java
g.res.setContentType("application/json");
g.res.setErrors(List.of(new ResponseError(Map.of("code", 401, "message", "This is error"))));
g.res.setStatusCode(555);
return "World";
```

**Kotlin**

**Content type JSON**

```kotlin
g.res.contentType = "application/json"
g.res.errors = listOf(ResponseError(mapOf("code" to 401, "message" to "This is error")))
g.res.statusCode = 555
return "World"
```

Response
```json
{
    "success": false,
    "statusCode": 555,
    "data": "World",
    "errors": [
        {
            "code": 401,
            "message": "This is error"
        }
    ],
    "warnings": []
}
```

### Bytes : application/octet-stream

**TypeScript**

**Content type OCTET_STREAM**

```typescript
g.res.contentType = T.EContentType.OCTET_STREAM;
```

**Python**

**Content type OCTET_STREAM**

```python
g.res.content_type = 'application/octet-stream'
```

**PHP**

**Content type OCTET_STREAM**

```php
$g->res->contentType = 'application/octet-stream';
```

**C#**

**Content type OCTET_STREAM**

```csharp
g.Res.ContentType = "application/octet-stream";
```

**Go**

**Content type OCTET_STREAM**

```go
g.Res.SetContentType("application/octet-stream")
```

**Rust**

**Content type OCTET_STREAM**

```rust
g.res.set_content_type("application/octet-stream");
```

**Java**

**Content type OCTET_STREAM**

```java
g.res.setContentType("application/octet-stream");
```

**Kotlin**

**Content type OCTET_STREAM**

```kotlin
g.res.contentType = "application/octet-stream"
```

- It will download the image.

**TypeScript**

**base64**

```typescript
g.res.contentType = 'image/gif' as T.EContentType;
return 'data:image/gif;base64,R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOwA=';
```

**Python**

**base64**

```python
g.res.content_type = 'image/gif'
return 'data:image/gif;base64,R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOwA='
```

**PHP**

**base64**

```php
$g->res->contentType = 'image/gif';
return 'data:image/gif;base64,R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOwA=';
```

**C#**

**base64**

```csharp
g.Res.ContentType = "image/gif";
return "data:image/gif;base64,R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOwA=";
```

**Go**

**base64**

```go
g.Res.SetContentType("image/gif")
return "data:image/gif;base64,R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOwA=", nil
```

**Rust**

**base64**

```rust
g.res.set_content_type("image/gif");
Ok(json!("data:image/gif;base64,R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOwA="))
```

**Java**

**base64**

```java
g.res.setContentType("image/gif");
return "data:image/gif;base64,R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOwA=";
```

**Kotlin**

**base64**

```kotlin
g.res.contentType = "image/gif"
return "data:image/gif;base64,R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOwA="
```

- It will send the bytes as they are : a file the code read or downloaded, a PDF it made. Return the bytes (a `Buffer`, `bytes`, `byte[]`, `[]byte`), or leave them in `g.res.output` : the answer is those bytes, under the content type the code names, whatever it is (`image/png`, `application/pdf`…). Headers of the code go with them (`Content-Disposition`, `Cache-Control`).

**TypeScript**

**bytes**

```typescript
const picture = Buffer.from('R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOwA=', 'base64');
g.res.contentType = 'image/gif' as T.EContentType;
g.res.headers = { 'Content-Disposition': 'inline; filename="pixel.gif"' };
return picture;
```

**Python**

**bytes**

```python
import base64

picture = base64.b64decode('R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOwA=')
g.res.content_type = 'image/gif'
g.res.headers = {'Content-Disposition': 'inline; filename="pixel.gif"'}
return picture
```

**PHP**

**bytes**

```php
// A text of PHP holds bytes too : AmBytes says that these are bytes.
$picture = base64_decode('R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOwA=');
$g->res->contentType = 'image/gif';
$g->res->headers = ['Content-Disposition' => 'inline; filename="pixel.gif"'];
return new AmBytes($picture);
```

**C#**

**bytes**

```csharp
var picture = Convert.FromBase64String("R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOwA=");
g.Res.ContentType = "image/gif";
g.Res.Headers = new JsonObject { ["Content-Disposition"] = "inline; filename=\"pixel.gif\"" };
return picture;
```

**Go**

**bytes**

```go
import "encoding/base64"

picture, err := base64.StdEncoding.DecodeString("R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOwA=")
if err != nil {
	return nil, err
}
g.Res.SetContentType("image/gif")
g.Res.SetHeaders(am.M{"Content-Disposition": `inline; filename="pixel.gif"`})
return picture, nil
```

**Rust**

**bytes**

```rust
// The bytes of the picture, as they are : a value of JSON has nothing which stands for bytes, `am::bytes` does.
let picture = b"GIF89a\x01\0\x01\0\x80\0\0\xff\xff\xff\xff\xff\xff!\xf9\x04\x01\n\0\x01\0,\0\0\0\0\x01\0\x01\0\0\x02\x02L\x01\0;\0";
g.res.set_content_type("image/gif");
g.res.set_headers(json!({ "Content-Disposition": "inline; filename=\"pixel.gif\"" }));
Ok(am::bytes(picture))
```

**Java**

**bytes**

```java
byte[] picture = Base64.getDecoder().decode("R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOwA=");
g.res.setContentType("image/gif");
g.res.setHeaders(Map.of("Content-Disposition", "inline; filename=\"pixel.gif\""));
return picture;
```

**Kotlin**

**bytes**

```kotlin
val picture = java.util.Base64.getDecoder().decode("R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOwA=")
g.res.contentType = "image/gif"
g.res.setHeaders(mapOf("Content-Disposition" to "inline; filename=\"pixel.gif\""))
return picture
```

### Text

**TypeScript**

**Content type TEXT**

```typescript
g.res.contentType = T.EContentType.TEXT;
return "Hello world from the API Maker.";
```

**Python**

**Content type TEXT**

```python
g.res.content_type = 'text/plain'
return 'Hello world from the API Maker.'
```

**PHP**

**Content type TEXT**

```php
$g->res->contentType = 'text/plain';
return 'Hello world from the API Maker.';
```

**C#**

**Content type TEXT**

```csharp
g.Res.ContentType = "text/plain";
return "Hello world from the API Maker.";
```

**Go**

**Content type TEXT**

```go
g.Res.SetContentType("text/plain")
return "Hello world from the API Maker.", nil
```

**Rust**

**Content type TEXT**

```rust
g.res.set_content_type("text/plain");
Ok(json!("Hello world from the API Maker."))
```

**Java**

**Content type TEXT**

```java
g.res.setContentType("text/plain");
return "Hello world from the API Maker.";
```

**Kotlin**

**Content type TEXT**

```kotlin
g.res.contentType = "text/plain"
return "Hello world from the API Maker."
```

Response
```text
Hello world from the API Maker.
```

### XML

**TypeScript**

**Content type XML**

```typescript
g.res.contentType = T.EContentType.XML;
return "Hello world from the API Maker.";
```

**Python**

**Content type XML**

```python
g.res.content_type = 'text/xml'
return 'Hello world from the API Maker.'
```

**PHP**

**Content type XML**

```php
$g->res->contentType = 'text/xml';
return 'Hello world from the API Maker.';
```

**C#**

**Content type XML**

```csharp
g.Res.ContentType = "text/xml";
return "Hello world from the API Maker.";
```

**Go**

**Content type XML**

```go
g.Res.SetContentType("text/xml")
return "Hello world from the API Maker.", nil
```

**Rust**

**Content type XML**

```rust
g.res.set_content_type("text/xml");
Ok(json!("Hello world from the API Maker."))
```

**Java**

**Content type XML**

```java
g.res.setContentType("text/xml");
return "Hello world from the API Maker.";
```

**Kotlin**

**Content type XML**

```kotlin
g.res.contentType = "text/xml"
return "Hello world from the API Maker."
```

Response
```xml
<?xml version='1.0'?>
<root>
    <success>true</success>
    <statusCode>200</statusCode>
    <data>Hello world from the API Maker.</data>
</root>
```

### YAML

**TypeScript**

**Content type YAML**

```typescript
g.res.contentType = T.EContentType.YAML;
return "Hello world from the API Maker.";
```

**Python**

**Content type YAML**

```python
g.res.content_type = 'text/yaml'
return 'Hello world from the API Maker.'
```

**PHP**

**Content type YAML**

```php
$g->res->contentType = 'text/yaml';
return 'Hello world from the API Maker.';
```

**C#**

**Content type YAML**

```csharp
g.Res.ContentType = "text/yaml";
return "Hello world from the API Maker.";
```

**Go**

**Content type YAML**

```go
g.Res.SetContentType("text/yaml")
return "Hello world from the API Maker.", nil
```

**Rust**

**Content type YAML**

```rust
g.res.set_content_type("text/yaml");
Ok(json!("Hello world from the API Maker."))
```

**Java**

**Content type YAML**

```java
g.res.setContentType("text/yaml");
return "Hello world from the API Maker.";
```

**Kotlin**

**Content type YAML**

```kotlin
g.res.contentType = "text/yaml"
return "Hello world from the API Maker."
```

Response
```yaml
success: true
statusCode: 200
data: Hello world from the API Maker.
```

## Related

- [The global object g](https://docs.apimaker.dev/v4/docs/pre-defined-terms/global-object-g.html) · [Response format](https://docs.apimaker.dev/v4/docs/apis-all/response-format.html) · [The request : g.req](https://docs.apimaker.dev/v4/examples/req/req.html)
