A JSON API in Go
An API returns data instead of pages. A Go struct becomes JSON with struct tags, a handler writes it with json.NewEncoder, and the page loads it with fetch.
Try it
- HTTP request builder – Choose a method, a path and a body, and see the exact request text and the response a pretend Go server would send.
Transcript
An A P I is a set of addresses that return data instead of web pages. The data is usually J S O N: text that both Go and JavaScript understand.
In Go, a struct turns into J S O N. Struct tags, written in backticks, say what each field is called in the J S O N, like json colon name.
A handler sets the content type header to application slash json, and then json dot NewEncoder writes the data to the response.
The page calls the same address with fetch, and shows what it gets. The browser and the Go server now talk to each other in J S O N.
Remember: an A P I returns data. A struct becomes J S O N, the encoder writes it, and fetch reads it in the page.
More in this series
1:2340How a web server works
A web server waits on a port for requests and sends responses. Handlers, http.HandleFunc and ListenAndServe, and seeing the request in the browser.
1:3041Routes, methods and status codes
A route connects a path and a method to a handler. GET, POST and DELETE, the status codes 200, 201, 400, 404 and 500, and how Go answers 404.
1:2143POST and saving data
A POST request carries data in its body. Decode the JSON into a struct, keep it in a slice (lost on restart), and protect the shared slice with a mutex.
1:1744What is a database?
A database keeps data in tables of rows and columns, like a strict spreadsheet. Primary keys, why data in a file survives a restart, and asking questions with SQL.
1:0145SQL basics
SQL is the language for asking a database: CREATE TABLE, INSERT INTO, SELECT with WHERE and ORDER BY, then UPDATE and DELETE (always with WHERE).
1:1446Go and databases
Go talks to a SQLite database with database/sql and a driver. Exec changes data, Query reads rows into structs, and ? placeholders pass values safely.
1:2047Input, validation and safety
Never trust a request: validate empty and too-long values and answer 400, why ? placeholders stop SQL injection, and keep secrets and database files out of Git.