Creating an http-endpoint

Hello Velo-Community,

i am on my way to discover the http-functions and how to use them (never really used them before).
I want to crete an http-endpoint, which will allow users to get data by using an http-request.

Because it is my first attempt to generate it, i have some diffculties to get it to work.

This is what i have right now…

import {ok, notFound, serverError} from 'wix-http-functions';
import wixData from 'wix-data';

export function get_myFunction(request) {
   let options = {
       "headers": {"Content-Type": "application/json"}
   };
 
  return wixData.query("Example-DB1")
  .find()
  .then((results) => {
      if(results.items.length > 0) {
         options.body = {"items": results.items};
         return ok(options);
      }
   });
}

Not sure if everything is coded the right way :sweat_smile::roll_eyes:
How i can test my generated code, if it is working or not?

1 Like

Ok, still no answer found on this topic.

To understand all this http-process better, i try to simplify it a little bit more…

Back-End-Code-Section:

import {ok} from 'wix-http-functions';

export function get_myFunction(request) {
   let options = {
      "headers": {"Content-Type": "application/json"},
      "body": "some text here"
   };
   return ok(options);
}}

Isn’t this all i need to create an http-endpoint?

My wished result is just the little STRING —> “some text here”, which should be shown like the result of this example-link…
https://api.exchangeratesapi.io/latest

When openening the related http-site directly in the browser, like this example-one:
https://user.wixsite.com/mysite/_functions/myFunction

Thnks so much! great

@certified-code
Need your help a little bit on this topic. Like i could see that you are online, right now. Would be great if you could give some hints on this. :roll_eyes:

OK, found an good example from Yisrael here…

also tried it out. It worked inside the example when i was requesting for example like… https://mt2-king.wixsite.com/mysite/_functions/recipe ,
but when i am doing the same thing on my own example, it doesn’t work at all.

I have right now copy and paste one of the given functions in the given example and modified it a little bit to my own needs.

import {ok, created, badRequest, notFound, serverError} from 'wix-http-functions';

export function get_xxx(request) {
   let options = {
        "headers": {
        "Content-Type": "application/json"
        }
    };

   let query = wixData.query("Team");
   if (request.query) {
   var query_keys = Object.keys(request.query);
        query_keys.forEach(function (entry) {
            query = query.contains(entry, request.query[entry]);
        });
    }
    return query
    .find()
    .then((results) => {
      //matching items were found
         if (results.items.length > 0) {
            options.body = {
                 "items": results.items
            };
            return ok(options);
        }
        
     // no matching items found
        options.body = {
            "error": `'${request.path[0]} ${request.path[1]}' was not found`
        };
        return notFound(options);
    })
 // something went wrong
    .catch((error) => {
        options.body = {
             "error": error
        };
        return serverError(options);
    });
}
  1. Collection-Name = “Team”
  2. Code is written down in the Back-End-Section (JSW-File)
  3. Function called —> “xxx” (get_xxx)

Why it is not working when i try to call this http-function with…
https://www.media-junkie. com/http-test/_functions/xxx

???

Start with a simple query and move up from there

import {response} from 'wix-http-functions';
import wixData from 'wix-data';

// You need to suppress authorization if your database has permissions
let full_suppress = {
   "suppressAuth": true,
   "suppressHooks": true
};

export function get_filter(request) {
    // First check if a query parameter is present in the request or not
    if(request.query) {
        return wixData.query("contact01") //remember to put a return here
        .find(full_suppress) //suppress authorization checks
        .then( (res) => {
             // Now check the length of the items retrieved
             if(res.items.length > 0) {
                 // Items found so return a 200 HTTP response
                 let options = {
                     status: 200,
                     body: res.items
                 };
                 return response(options); // similar to ok()
            } else {
                // No items found, return a 404 HTTP response
                let options = {
                     status: 404,
                     body: 'No items found'
                };
                return response(options); // similar to notFound()
            }
        })   
        .catch( (error) => {
             // This will catch any error with the wixdata query
             let options = {
                status: 500,
                body: error
             };
             return response(options); // similar to serverError()
        });
    } else {
         // Send a 400 response if no query params are found
         let options = {
            status: 400,
            body: 'No query parameters found'
         };
         return response(options); // similar to badRequest()
    }
}

Read my comments, this is a basic scenario on how to create a http function and get database items using an api call

Hmmmm sorry, still no luck! :expressionless:
What do i missing?

I modified your code like:


import {response} from 'wix-http-functions';
import wixData from 'wix-data';

// You need to suppress authorization if your database has permissions
let full_suppress = {
 "suppressAuth": true,
 "suppressHooks": true
};

export function get_filter(request) {
 // First check if a query parameter is present in the request or not
     if(request.query) {
        return wixData.query("Team") //remember to put a return here
        .find(full_suppress) //suppress authorization checks
        .then( (res) => {
            // Now check the length of the items retrieved
            if(res.items.length > 0) {
                // Items found so return a 200 HTTP response
                let options = {
                    status: 200,
                    body: res.items
                };
                return response(options); // similar to ok()
            } else {
                 // No items found, return a 404 HTTP response
                let options = {
                     status: 404,
                     body: 'No items found'
                };
                return response(options); // similar to notFound()
            }
        })   
        .catch( (error) => {
         // This will catch any error with the wixdata query
             let options = {
                status: 500,
                body: error
             };
             return response(options); // similar to serverError()
        });
     } else {
      // Send a 400 response if no query params are found
         let options = {
            status: 400,
            body: 'No query parameters found'
         };
         return response(options); // similar to badRequest()
    }
}

Tried to get results with…
https://www.media-junkie.com/http-test/_functions/filter
…after publishing website.

Still the same ERROR…

@russian-dima I think you have the incorrect database id. Note that database name and id can be different. Click on the database collection’s ‘Edit Settings’ to see the id.

@shantanukumar847


Any other ideas what could be wrong else?
The ID should be correct.

Also all permissions are given in this DATABASE.

@russian-dima can you screenshot your entire code along with the name of the backend file on the left hand side.

@shantanukumar847

@russian-dima You have the code on a .jsw file

HTTP functions can only be written in the http-functions.js file. Create a .js file and name it ’ http-functions

@shantanukumar847 Damn! I will do that! Thanks!

OK! I changed it, like you proposed it and also published it.
BUT! Still no changes :expressionless::expressionless::expressionless::disappointed_relieved:


Still not working.


Something else what i should change or add?

BTW: Thanks for your patience and effort to help me out, really appreciate it!

@russian-dima Take a closer look at your screenshot. You have created a public file not a backend file.

@shantanukumar847 Ok, i saw it. Perhaps i am already totaly overloaded xD.

I do some checks:

  1. Database published → checked !
  2. Database has right ID —> checked !
  3. Database has permissions —> checked !
  4. Using a JS-file instead of a JSW-file —> checked !
  5. Using the JS-File in the back-End —> checked !
  6. Gave the JS-File the right name → http-functions → checked !
  7. Added Shan’s CODE-Version and modified it —> checked :grin:!
  8. Published Website —> checked !
  9. Entered the following adress into my Google-Browser: checked !
    https://www.media-junkie.com/http-test/_functions/filter
  10. Did i forgot something else to check ?

  1. Disabled → CACHING → checked !
  2. Switched internet-connection to another one —> checked !

But still no RESULTS xDDDD :sleepy: HEEEEEEELP :laughing:!

BTW: Are you able to enter my DB, right now? :roll_eyes::roll_eyes::roll_eyes:

OK! I Think i’ve got it ! HURAAAAAAAY! :stuck_out_tongue_winking_eye::beers: