API Documentation

Complete reference for The Code Guy API

Getting Started

The Code Guy API provides simple REST endpoints for capturing screenshots, generating PDFs, and looking up UK postcode data.

  1. Create an account and add a project to get your API key
  2. Install our NuGet package or call the API directly
  3. Start using the Screenshot, PDF, and Postcode APIs

NuGet Packages

For .NET developers, we provide official NuGet packages that make integration simple.

TheCodeGuy.Screenshot
dotnet add package TheCodeGuy.Screenshot
using TheCodeGuy.Screenshot;

// Simple usage
var client = new ScreenshotClient("wt_your_api_key");
var imageBytes = await client.CaptureAsync("https://example.com");
await File.WriteAllBytesAsync("screenshot.png", imageBytes);

// With options
var result = await client.CaptureAsync(new ScreenshotRequest
{
    Url = "https://example.com",
    Width = 1920,
    Height = 1080,
    FullPage = true,
    Format = ImageFormat.Jpeg
});

Console.WriteLine($"Captured in {result.CaptureTimeMs}ms");
await File.WriteAllBytesAsync("screenshot.jpg", result.ImageBytes);
TheCodeGuy.Pdf
dotnet add package TheCodeGuy.Pdf
using TheCodeGuy.Pdf;

// Simple usage
var client = new PdfClient("wt_your_api_key");
var pdfBytes = await client.GenerateAsync("https://example.com");
await File.WriteAllBytesAsync("document.pdf", pdfBytes);

// With options
var result = await client.GenerateAsync(new PdfRequest
{
    Url = "https://example.com",
    Format = PageFormat.A4,
    Landscape = false,
    PrintBackground = true,
    DisplayHeaderFooter = true
});

Console.WriteLine($"Generated {result.PageCount} pages in {result.GenerationTimeMs}ms");
await File.WriteAllBytesAsync("document.pdf", result.PdfBytes);
Dependency Injection

Both packages support ASP.NET Core dependency injection:

// In Program.cs or Startup.cs
services.AddScreenshotClient("wt_your_api_key");
services.AddPdfClient("wt_your_api_key");

// Then inject into your services
public class MyService
{
    private readonly ScreenshotClient _screenshotClient;
    private readonly PdfClient _pdfClient;

    public MyService(ScreenshotClient screenshotClient, PdfClient pdfClient)
    {
        _screenshotClient = screenshotClient;
        _pdfClient = pdfClient;
    }
}

Authentication

All API requests require an API key. Include your key in the X-Api-Key header:

X-Api-Key: wt_your_api_key_here

Get your API key by creating an account and adding a project.

Screenshot API

POST /api/screenshot

Capture a screenshot of any webpage.

Request Body
Parameter Type Required Description
url string Yes The URL to capture. Must be a valid HTTP or HTTPS URL.
width integer No Viewport width in pixels. Default: 1920
height integer No Viewport height in pixels. Default: 1080
fullPage boolean No Capture the full scrollable page. Default: false
format string No "png" or "jpeg". Default: "png"
Example Code
// Install: dotnet add package TheCodeGuy.Screenshot
using TheCodeGuy.Screenshot;

var client = new ScreenshotClient("wt_your_api_key");

var result = await client.CaptureAsync(new ScreenshotRequest
{
    Url = "https://example.com",
    Width = 1920,
    Height = 1080,
    FullPage = false,
    Format = ImageFormat.Png
});

await File.WriteAllBytesAsync("screenshot.png", result.ImageBytes);
Console.WriteLine($"Captured in {result.CaptureTimeMs}ms");
using var client = new HttpClient();
client.DefaultRequestHeaders.Add("X-Api-Key", "wt_your_api_key");

var request = new
{
    url = "https://example.com",
    width = 1920,
    height = 1080,
    fullPage = false,
    format = "png"
};

var response = await client.PostAsJsonAsync(
    "https://api.thecodeguy.co.uk/api/screenshot",
    request);

var imageBytes = await response.Content.ReadAsByteArrayAsync();
await File.WriteAllBytesAsync("screenshot.png", imageBytes);
const response = await fetch('https://api.thecodeguy.co.uk/api/screenshot', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'X-Api-Key': 'wt_your_api_key'
    },
    body: JSON.stringify({
        url: 'https://example.com',
        width: 1920,
        height: 1080,
        fullPage: false,
        format: 'png'
    })
});

const blob = await response.blob();
// Use blob for download or display
import requests

response = requests.post(
    'https://api.thecodeguy.co.uk/api/screenshot',
    headers={'X-Api-Key': 'wt_your_api_key'},
    json={
        'url': 'https://example.com',
        'width': 1920,
        'height': 1080,
        'fullPage': False,
        'format': 'png'
    }
)

with open('screenshot.png', 'wb') as f:
    f.write(response.content)
Response

On success, returns the image with appropriate content type (image/png or image/jpeg).

The response includes a custom header X-Capture-Time-Ms indicating how long the capture took.

PDF API

POST /api/pdf

Convert any webpage to a multi-page PDF document.

Request Body
Parameter Type Required Description
url string Yes The URL to convert. Must be a valid HTTP or HTTPS URL.
format string No Page size: "A4", "Letter", "Legal", "Tabloid", "Ledger", "A0"-"A6". Default: "A4"
landscape boolean No Use landscape orientation. Default: false
printBackground boolean No Include background graphics and colors. Default: true
scale float No Scale of the webpage rendering (0.1 to 2.0). Default: 1.0
displayHeaderFooter boolean No Display page title and page numbers. Default: false
marginTop string No Top margin (e.g., "1cm", "0.5in", "20px")
marginBottom string No Bottom margin
marginLeft string No Left margin
marginRight string No Right margin
Example Code
// Install: dotnet add package TheCodeGuy.Pdf
using TheCodeGuy.Pdf;

var client = new PdfClient("wt_your_api_key");

var result = await client.GenerateAsync(new PdfRequest
{
    Url = "https://example.com",
    Format = PageFormat.A4,
    Landscape = false,
    PrintBackground = true,
    DisplayHeaderFooter = true
});

await File.WriteAllBytesAsync("document.pdf", result.PdfBytes);
Console.WriteLine($"Generated {result.PageCount} pages in {result.GenerationTimeMs}ms");
using var client = new HttpClient();
client.DefaultRequestHeaders.Add("X-Api-Key", "wt_your_api_key");

var request = new
{
    url = "https://example.com",
    format = "A4",
    landscape = false,
    printBackground = true,
    displayHeaderFooter = true
};

var response = await client.PostAsJsonAsync(
    "https://api.thecodeguy.co.uk/api/pdf",
    request);

var pdfBytes = await response.Content.ReadAsByteArrayAsync();
await File.WriteAllBytesAsync("document.pdf", pdfBytes);

// Get page count from response header
var pageCount = response.Headers.GetValues("X-Page-Count").FirstOrDefault();
const response = await fetch('https://api.thecodeguy.co.uk/api/pdf', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'X-Api-Key': 'wt_your_api_key'
    },
    body: JSON.stringify({
        url: 'https://example.com',
        format: 'A4',
        landscape: false,
        printBackground: true,
        displayHeaderFooter: true
    })
});

const pageCount = response.headers.get('X-Page-Count');
const blob = await response.blob();

// Download the PDF
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = 'document.pdf';
link.click();
import requests

response = requests.post(
    'https://api.thecodeguy.co.uk/api/pdf',
    headers={'X-Api-Key': 'wt_your_api_key'},
    json={
        'url': 'https://example.com',
        'format': 'A4',
        'landscape': False,
        'printBackground': True,
        'displayHeaderFooter': True
    }
)

page_count = response.headers.get('X-Page-Count')
print(f'Generated PDF with {page_count} pages')

with open('document.pdf', 'wb') as f:
    f.write(response.content)
Response

On success, returns the PDF with content type application/pdf.

Response headers include:

  • X-Generation-Time-Ms - Time taken to generate the PDF
  • X-Page-Count - Estimated number of pages in the PDF

Postcode API

Look up UK postcode data including coordinates, local authority, constituency, and more. Data sourced from the ONS Postcode Directory.

POST /api/postcode/lookup

Look up a single UK postcode.

Request Body
{ "postcode": "SW1A 1AA" }
Response
{
  "result": {
    "postcode": "SW1A 1AA",
    "outcode": "SW1A",
    "incode": "1AA",
    "latitude": 51.50101,
    "longitude": -0.141563,
    "easting": 529090,
    "northing": 179645,
    "country": "England",
    "region": "London",
    "localAuthority": "Westminster",
    "ward": "St James's",
    "constituency": "Cities of London and Westminster",
    "lsoa": "Westminster 018C",
    "msoa": "Westminster 018",
    "policeForce": "Metropolitan Police",
    "icb": "NHS North West London",
    "isActive": true
  }
}
POST /api/postcode/bulk

Look up multiple postcodes in a single request (max 100).

Request Body
{ "postcodes": ["SW1A 1AA", "EC1A 1BB", "M1 1AE"] }
Response
{
  "results": [ ... ],
  "found": 3,
  "notFound": 0
}
POST /api/postcode/validate

Check if a postcode exists in the database.

Request Body
{ "postcode": "SW1A 1AA" }
Response
{
  "postcode": "SW1A 1AA",
  "isValid": true
}
POST /api/postcode/nearest

Find postcodes nearest to a given latitude/longitude.

Request Body
Parameter Type Required Description
latitude number Yes Latitude (-90 to 90)
longitude number Yes Longitude (-180 to 180)
limit integer No Max results (1-100). Default: 10
radiusMetres number No Search radius (100-20000). Default: 2000
Example
{
  "latitude": 51.5074,
  "longitude": -0.1278,
  "limit": 5,
  "radiusMetres": 1000
}
POST /api/postcode/autocomplete

Autocomplete partial postcode (minimum 2 characters).

Request Body
{ "partial": "SW1A", "limit": 10 }
Response
{
  "postcodes": ["SW1A 0AA", "SW1A 0AB", "SW1A 1AA", ...]
}
Example Code
using var client = new HttpClient();
client.DefaultRequestHeaders.Add("X-Api-Key", "wt_your_api_key");

var response = await client.PostAsJsonAsync(
    "https://api.codeg.uy/api/postcode/lookup",
    new { postcode = "SW1A 1AA" });

var result = await response.Content.ReadFromJsonAsync<PostcodeLookupResponse>();
Console.WriteLine($"Local Authority: {result.Result.LocalAuthority}");
Console.WriteLine($"Coordinates: {result.Result.Latitude}, {result.Result.Longitude}");
const response = await fetch('https://api.codeg.uy/api/postcode/lookup', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'X-Api-Key': 'wt_your_api_key'
    },
    body: JSON.stringify({ postcode: 'SW1A 1AA' })
});

const data = await response.json();
console.log(`Local Authority: ${data.result.localAuthority}`);
console.log(`Coordinates: ${data.result.latitude}, ${data.result.longitude}`);
import requests

response = requests.post(
    'https://api.codeg.uy/api/postcode/lookup',
    headers={'X-Api-Key': 'wt_your_api_key'},
    json={'postcode': 'SW1A 1AA'}
)

data = response.json()
print(f"Local Authority: {data['result']['localAuthority']}")
print(f"Coordinates: {data['result']['latitude']}, {data['result']['longitude']}")

Usage API

GET /api/usage

Get usage statistics for your API key.

Example Code
using var client = new HttpClient();
client.DefaultRequestHeaders.Add("X-Api-Key", "wt_your_api_key");

var response = await client.GetAsync("https://api.thecodeguy.co.uk/api/usage");
var usage = await response.Content.ReadFromJsonAsync<UsageStats>();

Console.WriteLine($"Total requests: {usage.TotalRequests}");
Console.WriteLine($"Requests today: {usage.RequestsToday}");
const response = await fetch('https://api.thecodeguy.co.uk/api/usage', {
    headers: {
        'X-Api-Key': 'wt_your_api_key'
    }
});

const usage = await response.json();
console.log(`Total requests: ${usage.totalRequests}`);
console.log(`Requests today: ${usage.requestsToday}`);
import requests

response = requests.get(
    'https://api.thecodeguy.co.uk/api/usage',
    headers={'X-Api-Key': 'wt_your_api_key'}
)

usage = response.json()
print(f"Total requests: {usage['totalRequests']}")
print(f"Requests today: {usage['requestsToday']}")
Response
{
  "totalRequests": 150,
  "requestsToday": 25,
  "requestsThisMinute": 2,
  "averageResponseTimeMs": 1250.5,
  "lastRequestAt": "2024-01-15T10:30:00Z",
  "dailyUsage": [
    { "date": "2024-01-14", "requestCount": 50 },
    { "date": "2024-01-15", "requestCount": 25 }
  ]
}

Error Handling

Errors return appropriate HTTP status codes with a JSON body:

{
  "error": "Error message description"
}
Status Code Description
400 Bad Request - Invalid parameters or URL
401 Unauthorized - Missing or invalid API key
429 Too Many Requests - Rate limit exceeded
500 Internal Server Error

Rate Limits

Default rate limits per API key (free tier):

  • 5 requests per minute
  • 20 requests per day

When you exceed the rate limit, you'll receive a 429 response. Wait and try again.

Need higher limits? Contact us to discuss your requirements.