Fundamentals of building a Restful API with Django and django-rest-framework. Intended for new developers interested in developing a REST API for their applications. Basic knowledge of Python is nice to have, but the concepts are transferable.
Presented at Vancouver Python Day 2013.
2. Hi
•
Programming professionally for 10+ years
•
x86 assembly, STL, boost, python-boost, python
!
•
Built emacs-‐wiki-‐blog: first blogging engine for
Emacs!
3. SILOTA
•
Search As A Service
•
•
full stack: crawling, indexing, retrieving, tag deployment
Python shop:
•
•
ansible
•
sentry
•
django
•
•
pelican
django-‐rest-‐framework
In beta testing: love more feedback!
5. What is an API?
Application Programming Interface
!
An API is the interface implemented by an
application which allows other applications to
communicate with it.
7. What is REST?
•
REpresentational State Transfer
•
logical resources manipulated with HTTP verbs
•
modern best practice
•
wide adoption
•
contrast with SOAP
8. Why build an API?
•
explosion of devices connected to the internet
•
can be a company’s greatest asset
•
bizdev 2.0: internal developers, consultants,
partners, customers
19. Embrace HTTP
GET
/document
GET
/document/19
POST
/document
Retrieve all documents
Retrieve a specific document #19
Create a new document
PUT
/document/19
Update an existing document #19
DELETE
/document/19
Delete an existing document #19
23. Errors
<xml
version="1.0"?>
<Error>
<Message>A
server
error
has
occurred</Message>
<Description>Unknown
Error</Description>
<Id>1234</Id>
</Error>
Just no.
24. Errors
{
"code"
:
1234,
"message"
:
"Unsupported
media
type
‘text/html’
in
request",
"description"
:
"Requests
need
to
have
the
Content-‐Type
HTTP
header
set
to
‘application/json’"
}
27. Best practices
security
https all the way
base URLs
api.companyname.com
serialization
json
timestamps
ISO 8601 & UTC
versioning
/v1/
caching
ETag & Last-Modified
gzip
always & pretty print responses
logging
if possible
28. Recap
•
https + gzip + json
•
draw bipartite graph of nouns and verbs
•
great documentation
•
no surprises
34. Four step formula
1. create the model
2. write the serializer
3. write the view
4. configure the urls
35. References
•
How to Design a Good API and Why it Matters:
•
•
Best Practices for Designing a Pragmatic RESTful API
•
•
http://www.vinaysahni.com/best-practices-for-a-pragmaticrestful-api
REST worst practices:
•
•
http://lcsd05.cs.tamu.edu/slides/keynote.pdf
http://jacobian.org/writing/rest-worst-practices/
http://django-rest-framework.org/