GOT POST request examples – Headers, JSON, file upload

In this post, we have covered different types of GOT POST request examples, including sending simple data, form data,adding headers, dealing with JSON, and uploading files. Whether you’re new to Node.js or an experienced developer, these examples will help you understand how to effectively use got for your HTTP needs.

GOT POST request examples

Table of Contents

Simple GOT POST Request Example

Let’s start with a straightforward POST request using GOT. This example demonstrates a basic POST call to an API.

const got = require('got');

    async function makeSimplePost() {
        try {
            const response = await got.post('https://your.api/endpoint', {
                body: 'Hello, Server!'
            });
            console.log(response.body);
        } catch (error) {
            console.log(error.response.body);
        }
    }

    makeSimplePost();

POST Form Data

To send form data, use the form option instead of json. This is useful when interacting with APIs that expect form data.

async function postFormData() {
    try {
        const response = await got.post('https://your.api/endpoint', {
            form: {
                username: 'user',
                password: 'pass'
            }
        });

        console.log(response.body);
    } catch (error) {
        console.error(error.response.body);
    }
}

postFormData();

 

GOT POST Request with Custom Headers

When interacting with various APIs, the need to pass custom headers is a common requirement. Headers play a crucial role in conveying additional information like authentication tokens, content types, or other API-specific data. got simplifies this process, allowing developers to easily append custom headers to their requests. This capability is particularly useful in dealing with secure endpoints where tokens or API keys are necessary for access.

    async function postWithHeaders() {
        try {
            const response = await got.post('https://your.api/endpoint', {
                headers: {
                    'Authorization': 'Bearer your-token-here',
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: 'key1=value1&key2=value2'
            });
            console.log(response.body);
        } catch (error) {
            console.log(error.response.body);
        }
    }

    postWithHeaders();

Output:

Response with custom headers.

POSTing JSON Data

In the realm of API interaction, JSON is the lingua franca. The ability to handle JSON payloads efficiently is paramount. got shines here by offering a straightforward mechanism to send JSON data. This feature is particularly handy when dealing with RESTful APIs where the exchange of information in JSON format is standard practice. Whether it’s sending configuration data, user information, or complex objects, got ensures that your JSON payloads are correctly formatted and transmitted.

    async function postJson() {
        try {
            const response = await got.post('https://your.api/endpoint', {
                json: {
                    key1: 'value1',
                    key2: 'value2'
                },
                responseType: 'json'
            });
            console.log(response.body);
        } catch (error) {
            console.log(error.response.body);
        }
    }

    postJson();

Output:

JSON response from the server.

File Upload with POST Request

File uploads can be a challenging aspect of web development, often involving handling multipart data and stream management. got eases this complexity. It provides a seamless way to handle file uploads, whether it’s images, documents, or other binary data. This functionality is crucial for applications that require user-generated content or data import features. By streamlining the file upload process, got allows developers to focus more on the application logic rather than the nuances of file handling.

    const fs = require('fs');

    async function uploadFile() {
        try {
            const response = await got.post('https://your.api/endpoint', {
                body: fs.createReadStream('/path/to/your/file.jpg'),
                headers: {
                    'content-type': 'multipart/form-data'
                }
            });
            console.log(response.body);
        } catch (error) {
            console.log(error.response.body);
        }
    }

    uploadFile();

Output:

Server's response to file upload.

Conclusion

The got package is more than just a tool for making HTTP requests; it’s a comprehensive solution for modern web development challenges. By mastering these advanced features – custom headers, JSON payloads, and file uploads – developers can build more robust, efficient, and secure applications. As we continue to navigate the evolving landscape of web technologies, tools like got remain invaluable allies in the quest for better, faster, and more reliable web applications.

References