I m actually building a REST API that I need to test.
Actually, I have many unit tests to check each method behaviour and now I need to test if I get the expected result when requesting an endpoint, like checking the HTTP response code.
I m working with nodejs and it seems to be a good idea to use supertest module to send HTTP request and to check response codes.
The fact is that if I send request on my real REST API endpoints, I can have many bad data managed in database (when testing PUT / POST / PATCH methods).
But in the other hand, I don't have (in my mind) any way to "mock" or simulate my business job inside of the tests :
(Mocha syntax with ES6)
describe('get /v1/clients ', function() {
it('Should get 200 ', function(done) {
request.get('/v1/clients')
.query('access_token=' + token + '').expect(200, done);
});
});
So you've probably got it :
I want to test each API endpoint to be sure that I get what I should get
I want to use a standard access_token, not one my database (like a fake one)
I want to "simulate" by API, without using real data.
Is that possible ? If yes, How ?
Is this a better choice to check on my real data or not ?
Related
I am trying use an axios request to fetch data from github api, but for some reason _limit is not returning the limited number of results?
await axios.get(`https://api.github.com/users/freeCodeCamp/repos?_limit=10`)
.then(
(res) => {
console.log(res.data);
}
)
The following http request is working perfectly by limiting the results
https://jsonplaceholder.typicode.com/todos?_limit=2
Whereas the following http request is not limiting the data
https://api.github.com/users/freeCodeCamp/repos?_limit=2
What's the difference between the above two requests?
The _limit parameter you see in https://jsonplaceholder.typicode.com is specific to their json-server software.
From the Github REST API documentation, you want to use the per_page parameter
const { data } = await axios.get("https://api.github.com/users/freeCodeCamp/repos", {
params: {
per_page: 10
}
})
My general advice for using any REST API... always read the documentation specific to the resource you're consuming.
Sorting options for API results are limited to created, updated, pushed and full_name (default). If you want to sort by something else, you'll need to do that client-side, eg
data.sort((a, b) => a.stargazers_count - b.stargazers_count);
For GitHub, the correct property is per_page.
Just bear in mind that limiting results has nothing to do with Axios or any front-end tool. It is a backend implementation, and any backend developer is free to do it the way they want. Although there are some standards, such as cursor pagination.
In a real project, the backend and frontend developer would have a "contract" for how this would work, so both know how the property will work.
I am sorry for how I have framed the question in the title but I have started programming very recently so once again, I am really sorry.
I am developing a project with React js as my front-end and node js as my backend, I have been successful in doing some basic test api calls to confirm the connection between the two but now, how am I supposed to actually process different actions. For example, while a user is logging in, I need to first check if they are an existing user or not, sign them in if they are not, deleting a user account, changing username, etc.
I tried very hard to look for relevant articles but all I can find are basic "one-time" api calls, what am I supposed to do for an entire batch of operations? From what I have understood, the process of sending a request from React to getting it processed in Node js is like this:
react js ======>
(request for operation) node js ======>
(process the operation) ======>
send a response back to react
Please correct me if there are any mistakes in my question...
Thanks a lot!
This question is really broad, so I'm going to focus in on this part at a high level:
I tried very hard to look for relevant articles but all I can find are basic "one-time" api calls, what am I supposed to do for an entire batch of operations?
I'm guessing when you talk about requests and APIs you're talking about HTTP requests and REST APIs, which are fundamentally "stateless" kinds of things; HTTP requests are self-contained, and the backend doesn't have to keep track of any application state between requests in order to speak HTTP.
But backend applications usually do maintain state, often in the form of databases. For example, many REST APIs expose CRUD (create, read, update, and delete) operations for important business entities — in fact, Stack Overflow probably does exactly this for answers. When I post this answer, my browser will probably send some kind of a "create" request, and when I inevitably notice and fix a typo I will send some kind of "update" request. When you load it in your browser, you will send a "read" request which will get the text of the answer from Stack Overflow's database. Stack Overflow's backend keeps track of my answer between the requests, which makes it possible to send it to many users as part of many different requests.
Your frontend will have to do something similar if your project does things which involve multiple interdependent requests — for example, you would need to keep track of whether the user is authenticated or not in order to show them the login screen, and you would need to hold onto their authentication token to send along with subsequent requests.
Edit: Let's walk through a specific example. As a user, I want to be able to create and read notes. Each note should have a unique ID and a string for its text. On the backend, we'll have a set of CRUD endpoints:
var express = require(“express”);
var router = express.Router();
class Note {
constructor(id, text) {
this.id = id;
this.text = text;
}
}
// This is a quick and dirty database!
notes = {};
router.put("/note/:id", function(req, res) {
notes[req.params.id] = "hello"; // TODO: accept text as well
res.send("");
});
router.get(“/note/:id”, function(req, res) {
res.send(notes[req.params.id].text);
});
module.exports = router;
Then on the client side, one could create a note and then read it like this:
// this request will create the note
fetch("http://localhost:9000/note/42", { method: 'PUT', body: 'hello note!' });
// this request will read the note, but only after it is created!
fetch("http://localhost:9000/note/42")
.then(res => res.text())
.then(res => console.log(res));
I am new to node.js and am acquainting myself with Express. The following code is my source of confusion:
var server = http.createServer(handleRequest);
function handleRequest(req, res) {
var path = req.url;
switch (path) {
case "/n":
return renderPage_1(req, res);
default:
return renderPage_2(req, res);
}
}
I understand that the server needs to accept an HTTP request(req). However, if we are returning a response, why is the response also an argument in the callback function? I keep running into a dead-end thinking that it has to do with the scope of the response object, though I am not sure.
I would greatly appreciate clarification on this matter. I have not been able to find a resource that delineates my confusion.
Best,
Abid
I think the answer to your question is that this is how the authors of express decided to implement the library. At a high level, express is really just a light-ish weight wrapper that makes it easy to build middleware based http services with NodeJS. The reason that both the req & res objects are passed to each express middleware function is that in practice, web services are rarely able to fulfill an entire request in a single step. Often services are built as layer of middleware the build up a response in multiple steps.
For example, you might have a middleware function that looks for identity information in the request and fetches any relevant identity metadata while setting some auth specific headers on the response. The request might then flow to an authorization middleware that uses the fetched metadata to determine if the current user is authorized and if the user is not authorized can end the request early by closing the response stream. If the user is authorized then the request will continue to the next piece of middleware etc. To make this work, each middleware function (step of the stack) needs to be able to access information from the request as well as write information to the response. Express handles this by passing the request and response objects as arguments to the middleware function but this is just one way to do it.
Now the authors could have decided to implement the library differently such that each route handler was supposed to return an object such as { status: 200, content: "Hello, world" } instead of calling methods on the response object but this would be a matter of convention and you could pretty easily write a wrapper around express that let you write your services like this if you wanted.
Hope this helps.
I am new to the node JS ,In the nodeJS exercise no.8 of learnyounode ,my solution produces the same require result.I am confused when to use http.get and Request
goal:
Write a program that performs an HTTP GET request to a URL provided to you
as the first command-line argument. Collect all data from the server (not
just the first "data" event) and then write two lines to the console
(stdout).
The first line you write should just be an integer representing the number
of characters received from the server. The second line should contain the
complete String of characters sent by the server.
official solution
var http = require('http')
var bl = require('bl')
http.get(process.argv[2], function (response) {
response.pipe(bl(function (err, data) {
if (err)
return console.error(err)
data = data.toString()
console.log(data.length)
console.log(data)
}))
})
my solution
var request=require('request')
request(process.argv[2],function(err,response,body){
console.log(body.length);
console.log(body);
})
From nodeJS documentation:
Since most requests are GET requests without bodies, Node.js provides
this convenience method. The only difference between this method and
http.request() is that it sets the method to GET and calls req.end()
automatically. Note that response data must be consumed in the
callback for reasons stated in http.ClientRequest section.
So, what exactly that means, is that you could do it your way without any problem. But request is not a module shipped with node itself, it is a module to make http(s) requests easier on the developers. So I'm guessing here, that you are learning NodeJS and not using third-parties should be the way to go.
I'm not familiar with request but it's seems like it's just a npm package that wraps the functionality of the standard library. You can use both but I would suggest reading through the documentation of http.get and request and if you find the standard library function (http.get) sufficient for your needs I don' t see a reason you should use the request package.
I am using MeanJs Stack
I need to call the following Api :
http://localhost/api/movies/movieId/Action?page=1&perPage=10
How to send params (page='+:id+page='+pageNum+'&perPage='+perPage) in Server Route
I am sending the Following way which is not Helping
movies.server.routes.js
app.route('/api/movies/:id/Action?page='+:id+'page'=+pageNum+'&perPage'=+perPage')//But it is not recognising by rout and parameters are not sending
.get(movies.readAllMovies);//triggers and call the api .
Could you guys give me some Hint of it ?
Sorry for the horizontal scroll guys :-) .
Thanks.
According to ExpressJS documentation, query strings are not part of a route definition.
Therefore, your route could be refined (apart from having a couple of syntax errors) as such:
app.route('/api/movies/:id/Action')
.get(movies.readAllMovies);
Then, in the handler movies.readAllMovies, you can access query strings with req.query. That is, the page query string can be retried as req.query.page and so on.
Note that since expressJS uses regular expressions to match routes, a ? will serve as a quantifier in regular expression terms.
First of all, in my opinion, you should be handling this through a service to return the result, and a RESTful endpoint on the node server to perform the query. I feel your above approach could use a serious re-visit conceptually, so here's how I'd tackle it.
You need to create a service or a factory for handling the requests to the api endpoint
Check out the below instructions for modifying your api endpoint so that it just pipes the response back to the service
Include the service in your angular module and consume it on demand in your controller / whatever
You should use request module and params, it is by far the easiest method of retrieving query params in get requests in my opinion and streaming the response is to just pipe the result of the url. This is super simple using request https://www.npmjs.com/package/request
First, lets modify your endpoint and include the request module
First npm install request --save
Then in your app include request var request = require('request');
req.query.--name of queryparam
and
req.params.--name of param
Then your endpoint is as simple as
app.get('/api/movies/:movieID/:Category', function(req, res){
var url='http://localhost/api/movies/' + req.params.movieID + '/' + req.params.Category +'?page=' + req.query.page + '&perPage=' + + req.query.page;
request(url).pipe(res);
});
**You should be able to hit this endpoint directly with a get request and it should work
Then Create a Service to consume the result and provide it to the controller