Reputation: 7571
I need a live test server that accepts my requests for basic information via HTTP GET and also allows me to POST (even if it's really not doing anything). This is entirely for test purposes.
A good example is here. It easily accepts GET requests, but I need one that accepts POST requests as well.
Does anyone know of a server that I can send dummy test messages too?
Upvotes: 660
Views: 677320
Reputation: 383050
nc
one-liner Linux local test server
Run a local test server that prints requests and does not reply with the Ubuntu pre-installed nc
utility:
nc -kdl 8000
To actually send a minimal empty HTTP reply back in order to unblock HTTP clients such as wget
that wait for a reply so you can do more tests afterwards on the other shell without manually interrupting the client (thanks to nikniknik and zelanix in the comments):
while true; do printf 'HTTP/1.1 200 OK\r\n\r\n' | nc -Nl 8000; done
And if you want to get real fancy and actually send the date on the reply body:
while true; do
resp=$"$(date): hello\n"
len="$(printf '%s' "$resp" | wc -c)"
printf "HTTP/1.1 200 OK\r\nContent-Length: $len\r\n\r\n${resp}\n" | nc -Nl 8000
done
Sample request maker on another shell:
curl -vvv localhost:8000
then on the shell with the server you see the request showed up:
GET / HTTP/1.1
Host: localhost:8000
User-Agent: curl/8.2.1
Accept: */*
And on the server version where we return the date, on the request maker shell we can see a reply like:
Thu Dec 14 12:08:33 PM GMT 2023: hello
nc
from the netcat-openbsd
package is widely available and pre-installed on most Ubuntu.
For even more fun, this is a fine IasS hello world test of your favorite provider, e.g. I've recently done this from AWS EC2 Ubuntu image and it worked well after port 80 was opened in the security settings: Opening port 80 EC2 Amazon web services
Related questions about the minimal value HTTP reply:
Related:
Tested on Ubuntu 22.10, nc
from netcat-openbsd 1.218.
python -m http.server
local file server
This one is also handy, it serves files from the current working directory, so it gives you a simple way to setup different answers to different requests.
Create two test files:
echo aaa > bbb
echo 000 > 111
Runt the server on the default port 8000:
python -m http.server
Query one of the paths:
curl -vvv http://localhost:8000/bbb
Output:
* Host localhost:8000 was resolved.
* IPv6: ::1
* IPv4: 127.0.0.1
* Trying [::1]:8000...
* connect to ::1 port 8000 from ::1 port 33928 failed: Connection refused
* Trying 127.0.0.1:8000...
* Connected to localhost (127.0.0.1) port 8000
> GET /bbb HTTP/1.1
> Host: localhost:8000
> User-Agent: curl/8.5.0
> Accept: */*
>
* HTTP 1.0, assume close after body
< HTTP/1.0 200 OK
< Server: SimpleHTTP/0.6 Python/3.12.3
< Date: Wed, 13 Nov 2024 07:44:23 GMT
< Content-type: application/octet-stream
< Content-Length: 4
< Last-Modified: Wed, 13 Nov 2024 07:43:43 GMT
<
aaa
* Closing connection
Upvotes: 66
Reputation: 481
If you have python setup, use the following code to run a local http echo server.
Save the following file as server.py.
import socket
import json
from datetime import datetime
port = 3001
print(f"Listening to http://localhost:{port}")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('localhost', port))
s.listen(5)
while True:
client, _ = s.accept()
data = client.recv(1024).decode()
if data:
headers, _, body = data.partition('\r\n\r\n')
method, url, _ = headers.split('\r\n')[0].split(' ')
print(f"Timestamp: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
print(f"Request method: {method}")
print(f"URL: {url}")
print("Request headers:")
for header in headers.split('\r\n')[1:]:
if ': ' in header:
print(header)
print("Request body:")
print(body)
print("===================")
# Send a 200 OK response with a dummy JSON
dummy_json = {'message': 'Hello, client!'}
response_body = json.dumps(dummy_json)
response = f"HTTP/1.1 200 OK\r\nContent-Length: {len(response_body)}\r\nConnection: close\r\nContent-Type: application/json\r\n\r\n{response_body}"
client.sendall(response.encode())
client.close()
The code will accept all types of incoming http requests and prints the request headers, path and payload info. It will return 200 response with the static json response. Modify the response as per your need.
Run
python3 server.py
Sample usage:
curl -X POST -d "Hello server" http://localhost:3001/test
Sample logs:
Request method: POST
URL: /test
Request headers:
Host: localhost:3001
User-Agent: curl/8.4.0
Accept: */*
Content-Length: 12
Content-Type: application/x-www-form-urlencoded
Request body:
Hello server
===================
Upvotes: 0
Reputation: 2483
This repo https://github.com/mccutchen/go-httpbin is a reimplementation in go of almost all endpoints from the orignal python version.
A reasonably complete and well-tested golang port of Kenneth Reitz's httpbin service, with zero dependencies outside the go stdlib.
It is available online at https://httpbingo.org/
Upvotes: 6
Reputation: 161
Another one that offers some customization and is easy to use (no install, signup) is Beeceptor. You create an endpoint, make an initial request to it, and can tweak the responses.
Beeceptor goes beyond just an HTTP inspection tool. You can do more:
HTTP intercept and inspection:
A mock server - send desired HTTP responses. You can define rules to matching requests based on routes/paths. Beeceptor's mocking templates are quite powerful, allowing you to pick query params and send in the response payload.
Reverse-proxy: A MITM or a reverse proxy that lets you route the incoming request to destination server, and inspect the traffic. This is quite handy when debugging payloads which are not logged in application logs.
Upvotes: 5
Reputation: 5151
I don't konw why all of the answers here make a very simple work very hard!
When there is a request on HTTP, actually a client will send a HTTP_MESSAGE to server (read about what is HTTP_MESSAGE) and you can make a server in just 2 simple steps:
Install netcat:
In many unix-based systems you have this already installed and if you have windows just google it , the installation process is really simple, you just need a nc.exe file and then you should copy the path of this nc.exe file to your path environment variable and check if every thing is OK with nc -h
Make a server which is listening on localhost:12345
:
just type nc -l -p 12345
on your terminal and everything is done! (in mac nc -l 12345
tnx Silvio Biasiol)
Now you have a server (not a real web server, just a network listener) which is listening on http://localhost:12345
, for example you can make a post request with axios If you are a js developer:
axios.post('http://localhost:12345', { firstName: 'Fred' })
or make your own xhr
or make a form in a HTML file and submit it to server, sth. like:
<form action="http://localhost:12345" method="post">
or make a request with curl
or wget
or etc. Then check your terminal, a raw HTTP_MESSAGE should be appear on your terminal and you can start your happy hacking ;)
Upvotes: 6
Reputation: 20891
I like using reqres.in, it simply opens the use of basic methods of HTTP.
Upvotes: 0
Reputation: 66771
Here is one Postman echo: https://postman-echo.com
example:
curl --request POST \
--url https://postman-echo.com/post \
--data 'This is expected to be sent back as part of response body.'
response:
{"args":{},"data":"","files":{},"form":{"This is expected to be sent back as part of response body.":""},"headers":{"host":"postman-echo.com","content-length":"58","accept":"*/*","content-type":"application/x-www-form-urlencoded","user-agent":"curl/7.54.0","x-forwarded-port":"443","x-forwarded-proto":"https"},"json":{"...
Upvotes: 19
Reputation: 2049
There is ptsv3.com
"Here you will find a server which receives any POST you wish to give it and stores the contents for you to review."
Upvotes: 178
Reputation: 121
I am using this REST API all the time: https://restful-api.dev
It stores the created objects indefinitely. Also, the schema is quite flexible, you can pass any JSON data.
I am a Front-End developer and is very useful when I need to create some sample data. This is the only one I could find that does it for free without any registration or tokens.
Upvotes: 0
Reputation: 6511
I am not sure if anyone would take this much pain to test GET and POST calls. I took Python Flask module and wrote a function that does something similar to what @Robert shared.
from flask import Flask, request
app = Flask(__name__)
@app.route('/method', methods=['GET', 'POST'])
@app.route('/method/<wish>', methods=['GET', 'POST'])
def method_used(wish=None):
if request.method == 'GET':
if wish:
if wish in dir(request):
ans = None
s = "ans = str(request.%s)" % wish
exec s
return ans
else:
return 'This wish is not available. The following are the available wishes: %s' % [method for method in dir(request) if '_' not in method]
else:
return 'This is just a GET method'
else:
return "You are using POST"
When I run this, this follows:
C:\Python27\python.exe E:/Arindam/Projects/Flask_Practice/first.py
* Restarting with stat
* Debugger is active!
* Debugger PIN: 581-155-269
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
Now lets try some calls. I am using the browser.
This is just a GET method
http://127.0.0.1:5000/method/NotCorrect
This wish is not available. The following are the available wishes:
['application', 'args', 'authorization', 'blueprint', 'charset', 'close', 'cookies', 'data', 'date', 'endpoint', 'environ', 'files', 'form', 'headers', 'host', 'json', 'method', 'mimetype', 'module', 'path', 'pragma', 'range', 'referrer', 'scheme', 'shallow', 'stream', 'url', 'values']
http://127.0.0.1:5000/method/environ
{'wsgi.multiprocess': False, 'HTTP_COOKIE': 'csrftoken=YFKYYZl3DtqEJJBwUlap28bLG1T4Cyuq', 'SERVER_SOFTWARE': 'Werkzeug/0.12.2', 'SCRIPT_NAME': '', 'REQUEST_METHOD': 'GET', 'PATH_INFO': '/method/environ', 'SERVER_PROTOCOL': 'HTTP/1.1', 'QUERY_STRING': '', 'werkzeug.server.shutdown': , 'HTTP_USER_AGENT': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36', 'HTTP_CONNECTION': 'keep-alive', 'SERVER_NAME': '127.0.0.1', 'REMOTE_PORT': 49569, 'wsgi.url_scheme': 'http', 'SERVER_PORT': '5000', 'werkzeug.request': , 'wsgi.input': , 'HTTP_HOST': '127.0.0.1:5000', 'wsgi.multithread': False, 'HTTP_UPGRADE_INSECURE_REQUESTS': '1', 'HTTP_ACCEPT': "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", 'wsgi.version': (1, 0), 'wsgi.run_once': False, 'wsgi.errors': ", mode 'w' at 0x0000000002042150>", 'REMOTE_ADDR': '127.0.0.1', 'HTTP_ACCEPT_LANGUAGE': 'en-US,en;q=0.8', 'HTTP_ACCEPT_ENCODING': 'gzip, deflate, sdch, br'}
Upvotes: 1
Reputation: 31706
You can run the actual Ken Reitz's httpbin
server locally (under docker or on bare metal):
https://github.com/postmanlabs/httpbin
docker pull kennethreitz/httpbin
docker run -p 80:80 kennethreitz/httpbin
## install dependencies
pip3 install gunicorn decorator httpbin werkzeug Flask flasgger brotlipy gevent meinheld six pyyaml
## start the server
gunicorn -b 0.0.0.0:8000 httpbin:app -k gevent
Now you have your personal httpbin instance running on http://0.0.0.0:8000 (visible to all of your LAN)
I wanted a server which returns predefined responses so I found that in this case it's simpler to use a minimal Flask app:
#!/usr/bin/env python3
# Install dependencies:
# pip3 install flask
import json
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def root():
# spit back whatever was posted + the full env
return jsonify(
{
'request.json': request.json,
'request.values': request.values,
'env': json.loads(json.dumps(request.__dict__, sort_keys=True, default=str))
}
)
@app.route('/post', methods=['GET', 'POST'])
def post():
if not request.json:
return 'No JSON payload! Expecting POST!'
# return the literal POST-ed payload
return jsonify(
{
'payload': request.json,
}
)
@app.route('/users/<gid>', methods=['GET', 'POST'])
def users(gid):
# return a JSON list of users in a group
return jsonify([{'user_id': i,'group_id': gid } for i in range(42)])
@app.route('/healthcheck', methods=['GET'])
def healthcheck():
# return some JSON
return jsonify({'key': 'healthcheck', 'status': 200})
if __name__ == "__main__":
with app.test_request_context():
app.debug = True
app.run(debug=True, host='0.0.0.0', port=8000)
Upvotes: 9
Reputation: 1827
Create choose a free web host and put the following code
<h1>Request Headers</h1>
<?php
$headers = apache_request_headers();
foreach ($headers as $header => $value) {
echo "<b>$header:</b> $value <br />\n";
}
?>
Upvotes: 4
Reputation: 2696
You might don't need any web site for that, only open up the browser, press F12
to get access to developer tools > console, then in console write some JavaScript Code to do that.
Here I share some ways to accomplish that:
For GET request: *.Using jQuery:
$.get("http://someurl/status/?messageid=597574445", function(data, status){
console.log(data, status);
});
For POST request:
$.ajax
:var url= "http://someurl/",
api_key = "6136-bc16-49fb-bacb-802358",
token1 = "Just for test",
result;
$.ajax({
url: url,
type: "POST",
data: {
api_key: api_key,
token1: token1
},
}).done(function(result) {
console.log("done successfuly", result);
}).fail(function(error) {
console.log(error.responseText, error);
});
var merchantId = "AA86E",
token = "4107120133142729",
url = "https://payment.com/Index";
var form = `<form id="send-by-post" method="post" action="${url}">
<input id="token" type="hidden" name="token" value="${merchantId}"/>
<input id="merchantId" name="merchantId" type="hidden" value="${token}"/>
<button type="submit" >Pay</button>
</div>
</form> `;
$('body').append(form);
$("#send-by-post").submit();//Or $(form).appendTo("body").submit();
`var api_key = "73736-bc16-49fb-bacb-643e58",
recipient = "095552565",
token1 = "4458",
url = 'http://smspanel.com/send/';`
``var form = `<form id="send-by-post" method="post" action="${url}">
<input id="api_key" type="hidden" name="api_key" value="${api_key}"/>
<input id="recipient" type="hidden" name="recipient" value="${recipient}"/>
<input id="token1" name="token1" type="hidden" value="${token1}"/>
<button type="submit" >Send</button>
</div>
</form>`;``
document.querySelector("body").insertAdjacentHTML('beforeend',form);
document.querySelector("#send-by-post").submit();
var url = "https://Payment.com/index";
Response.Clear();
var sb = new System.Text.StringBuilder();
sb.Append("<html>");
sb.AppendFormat("<body onload='document.forms[0].submit()'>");
sb.AppendFormat("<form action='{0}' method='post'>", url);
sb.AppendFormat("<input type='hidden' name='merchantId' value='{0}'>", "C668");
sb.AppendFormat("<input type='hidden' name='Token' value='{0}'>", "22720281459");
sb.Append("</form>");
sb.Append("</body>");
sb.Append("</html>");
Response.Write(sb.ToString());
Response.End();
Upvotes: 1
Reputation: 15726
It echoes the data used in your request for any of these types:
Upvotes: 1062
Reputation: 29
If you need or want a simple HTTP server with the following:
I built one on top of the excellent SimpleHTTPAuthServer already on PyPI. This adds handling of POST requests: https://github.com/arielampol/SimpleHTTPAuthServerWithPOST
Otherwise, all the other options publicly available are already so good and robust.
Upvotes: 1
Reputation: 23757
Webhook Tester is a great tool: https://webhook.site (GitHub)
Important for me, it showed the IP of the requester, which is helpful when you need to whitelist an IP address but aren't sure what it is.
Upvotes: 85
Reputation: 2828
http://requestb.in was similar to the already mentioned tools and also had a very nice UI.
RequestBin gives you a URL that will collect requests made to it and let you inspect them in a human-friendly way. Use RequestBin to see what your HTTP client is sending or to inspect and debug webhook requests.
Though it has been discontinued as of Mar 21, 2018.
We have discontinued the publicly hosted version of RequestBin due to ongoing abuse that made it very difficult to keep the site up reliably. Please see instructions for setting up your own self-hosted instance.
Upvotes: 40
Reputation: 31171
If you want a local test server that accepts any URL and just dumps the request to the console, you can use node:
const http = require("http");
const hostname = "0.0.0.0";
const port = 3000;
const server = http.createServer((req, res) => {
console.log(`\n${req.method} ${req.url}`);
console.log(req.headers);
req.on("data", function(chunk) {
console.log("BODY: " + chunk);
});
res.statusCode = 200;
res.setHeader("Content-Type", "text/plain");
res.end("Hello World\n");
});
server.listen(port, hostname, () => {
console.log(`Server running at http://localhost:${port}/`);
});
Save it in a file 'echo.js' and run it as follows:
$ node echo.js
Server running at http://localhost:3000/
You can then submit data:
$ curl -d "[1,2,3]" -XPOST http://localhost:3000/foo/bar
which will be shown in the server's stdout:
POST /foo/bar
{ host: 'localhost:3000',
'user-agent': 'curl/7.54.1',
accept: '*/*',
'content-length': '7',
'content-type': 'application/x-www-form-urlencoded' }
BODY: [1,2,3]
Upvotes: 40
Reputation: 545
https://www.mockable.io. It has nice feature of getting endpoints without login (24h temporary account)
Upvotes: 7
Reputation: 3927
I have created an open-source hackable local testing server that you can get running in minutes. You can create new API's, define your own response and hack it in any ways you wish to.
Github Link : https://github.com/prabodhprakash/localTestingServer
Upvotes: 4
Reputation: 6357
Have a look at PutsReq, it's similar to the others, but it also allows you to write the responses you want using JavaScript.
Upvotes: 35
Reputation: 17
Just set one up yourself. Copy this snippet to your webserver.
echo "<pre>"; print_r($_POST); echo "</pre>";
Just post what you want to that page. Done.
Upvotes: -18