Python SimpleHTTPServer for testing

Posted on Wednesday, February 17, 2016

The other day I had a need to set up a very simple web server just so I could easily see the header information it was getting.

Ideally I just wanted a simple command line tool I could use.  So that I could bring it up quickly and watch it from the command line as Header … etc information scrolled by.   I just needed something for local testing.

While poking around I found this SimpleHTTPServer.   You can run this from the command line.

   > python -m SimpleHTTPServer

A simple web server starts up and listens on port 8000.

And you will see the contents of the folder you started the web server in.

Click and download away.

That is pretty neat and useful in and of itself, but it also outputs a little bit of data.

I want it to output some more data than that like Headers.

I  found a few examples out there

Here is what I came up with.

   > vi

And here is the raw code.

How to use it

First make it executable

   > chmod u+x

Then run it

   > ./

This will open a simple web server using port 8080
You can test it by opening a browser and going to http://localhost:8080/

It outputs the Header information so you can see it.

Or you could use a simple curl to test it.

   > curl --header "X-MyHeader: test-X"  http://localhost:8080/

There is my header.

Also you can change what port to listen to.

   > ./ -p 9090

You can also turn on the ability to POST

   > ./ -p 9090 --POST on

Then you can post data to it like the following.

   > curl -i -d '{"json":"TEST"}' http://localhost:8080/test2

This will save the posted data to a file (in my test case test2)

It won't overwrite existing files.
There is not a lot to this simple web server, a lot more can be added to it.  I just needed a simple tool I could bring up for a few local test of my software.

With that in mind I want to just move it to a command in /usr/bin/

   > cp /usr/bin/webserver

Now I can just call it with

   > webserver

I am sure I will tweak it in the future but for now it meet my testing needs.


[1]        gist simpleHTTPServer with headers by phrawzty                
                 Accessed 02/2016
[2]        Simple HTTP server for testing GET and POST requests. Python 3.    
                 Accessed 06/2014

No comments:

Post a Comment