OpenAPI and DRF Serializers

OpenAPI

Describes a RESTful API

Is it useful?

  • Autogenerate client (see apistar)
  • Automatic documentation (supports confluence)
  • Language agnostic
  • Mock API servers
  • Automated tests for your API (eg: soapui)

How are serializers related to openAPI?

what

Most of DRF elements (serializers, filters, responses)

map directly to a part of a REST API

Serializers map directly to the HTTP BODY

(THE PAYLOAD)

http request
What are they for?
Do's and Don'ts of serializers
Do's
  • Validate input data
  • Clean input data
  • Deserialize (most of the times)
Don'ts
  • ❌ Querystrings
  • ❌ Headers
  • ❌ Pagination
  • ❌ input/output serializers

Do we need output serializer?

Does it have an impact on performance?

No, we don't need them

Yes, it has an impact on performance

output serializer is 41% slower

540.8ms vs 917.4ms on average

(sorry for the cheap benchmarks)

Some alternatives
  • Follow REST principles and work with the same resource
  • Use read_only_fields or write_only
  • Use to_representation or to_internal_value

DRY

Some stats:

APIView: 278

ModelViewSet: 17

APIView vs ViewSet -- DEMO TIME

on_fire

How to deal with querystrings?

Django filter

  1. Similar to serializers (declarative)
  2. Can raise 400s if needed
  3. Creates OpenAPI representation

Dealing with sensitive information in querystrings

use HEADERS

Find me on twitter

@santiwilly